我有一个应用程序应该向 URL 发送 GET 请求并连同它一起发送一些 cookie。我一直在查看 BasicCookieStore 和 Cookie 类的一些代码示例,但我无法弄清楚如何使用它们。谁能指出我正确的方向?
最佳答案
要使用 cookie,您需要遵循以下原则:
CookieStore cookieStore = new BasicCookieStore();
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext ctx = new BasicHttpContext();
ctx.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet get = new HttpGet("your URL here");
HttpResponse response = httpclient.execute(get,ctx);
如果你想在请求之间保留 cookie,你必须为每个请求重用 cookieStore
和 ctx
。
另外,你可以阅读你的 cookieStore
看看里面有什么:
List<Cookie> cookies = cookieStore.getCookies();
if( !cookies.isEmpty() ){
for (Cookie cookie : cookies){
String cookieString = cookie.getName() + " : " + cookie.getValue();
Log.info(TAG, cookieString);
}
}
关于java - Android BasicCookieStore、Cookies 和 HttpGet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13556712/