有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java消费web服务和存储cookie

此方法用于使用我也控制的web服务。web服务设置cookie以保持用户登录

这一切都可以通过浏览器正常工作。i、 e.我可以调用登录url,它将对我的浏览器进行cookie操作,随后对web服务的访问将识别我的cookie

在安卓系统中,我可以在登录时成功返回,但cookies似乎没有设置

您可以看到这段代码将cookie数据打印到输出的位置。当点击登录脚本时,它会打印cookie,但对于后续调用此函数,它不再识别cookie

以下是我使用的代码,我从其他人发布的一个示例开始:

private JSONObject getResponse(String func, List<NameValuePair> args) throws Exception {

    HttpClient httpclient = new DefaultHttpClient();
    try {
        // Create a local instance of cookie store
        CookieStore cookieStore = new BasicCookieStore();

        // Create local HTTP context
        HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpPost put= new HttpPost("http://example.com/api/" + func);
        if (args != null) {
            put.setEntity(new UrlEncodedFormEntity(args));
        }

        System.out.println("executing request " + put.getURI());

        // Pass local context as a parameter
        HttpResponse response = httpclient.execute(put, localContext);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }

        // Consume response content
        //EntityUtils.consume(entity);
        System.out.println("----------------------------------------");

        InputStream instream = entity.getContent();
        String result = convertStreamToString(instream);
        instream.close();
        entity.consumeContent();

        System.out.println("JSON Output: " + result);

        return new JSONObject(result);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

共 (2) 个答案

  1. # 1 楼答案

    这可能是因为您的HttpClient和CookieStore对于getResponse来说是本地的。试着让他们全球化,这样他们就可以坚持后续通话

  2. # 2 楼答案

    当您试图访问url呼叫中的锁定内容时,您需要为下一次呼叫手动设置cookie,这可以通过以下方式完成:

    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setInstanceFollowRedirects(false);
    
    httpURLConnection.setRequestProperty("Host", domainOfYourCookie);
    httpURLConnection.setRequestProperty("Cookie", valueOfYourCookie);
    

    关于这个话题,我写了另一个答案,你可以找到here