此方法用於消費我也控制的網絡服務。網絡服務設置cookie以保持用戶登錄。消費網絡服務和存儲cookies
這一切都通過瀏覽器正常工作。即我可以調用登錄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();
}
}