消费网络服务&存储cookie

时间:2011-07-19 17:01:55

标签: java android httpclient

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

这一切都可以通过浏览器正常工作。即我可以调用登录URL,它会为我的浏览器添加cookie,随后访问Web服务会识别我的cookie。

在android中,我可以在登录时获得成功的回报,但cookie似乎没有设置。

您可以看到此代码将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 个答案:

答案 0 :(得分:3)

这可能是因为您的HttpClient和CookieStore是getResponse的本地。尝试将它们设为全局,以便它们能够持续进行后续调用。

答案 1 :(得分:2)

当您尝试在网址调用中访问已锁定的内容时,您需要为下一次调用手动设置Cookie,这可以通过以下方式完成:

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setInstanceFollowRedirects(false);

httpURLConnection.setRequestProperty("Host", domainOfYourCookie);
httpURLConnection.setRequestProperty("Cookie", valueOfYourCookie);

我已就此主题撰写了另一个答案,您可以找到here