java - 使用网络服务并存储 cookie

标签 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();
    }
}

最佳答案

这可能是因为您的 HttpClient 和 CookieStore 对于 getResponse 来说是本地的。尝试使它们成为全局的,以便它们持续到后续调用中。

关于java - 使用网络服务并存储 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6751054/

相关文章:

android - Android 中 HttpUrlConnection 的编码问题

java - 馆藏副本

java - Apache Flink writeAsCsv() 方法写入对象元组

android - 如何使用 Android 通过 3G 连接到手机

tomcat - Tomcat 6 中的 sun.net.www.http.HttpClient 内存泄漏

c# - 使用 .Result 的异步方法

java - JSP 等同于 json_encode(在 PHP 中)是什么?

java - (isUserInRole()) 是将用户权限/安全性附加到 JSF 按钮的最简单方法吗?

java - 选择ListPreference时播放声音

android - 为什么滚动时ListView item中的文字消失了?