【发布时间】:2011-07-20 01:18:58
【问题描述】:
此方法用于使用我也控制的 Web 服务。 Web 服务设置 cookie 以保持用户登录。
这一切都可以通过浏览器正常工作。即我可以调用登录 url,它会 cookie 我的浏览器,随后访问网络服务会识别我的 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();
}
}
【问题讨论】:
标签: java android httpclient