Android BasicCookieStore,Cookies和HttpGet

时间:2012-11-25 23:30:10

标签: java android cookies http-get cookiestore

我有一个应用程序应该向URL发送GET请求并随之发送一些cookie。我一直在查看BasicCookieStore和Cookie类的一些代码示例,但我无法弄清楚如何使用它们。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

要使用cookies,您需要以下内容:

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,则必须为每个请求重复使用cookieStorectx

另外,您可以阅读cookieStore以查看其中的内容:

List<Cookie> cookies = cookieStore.getCookies();
if( !cookies.isEmpty() ){
    for (Cookie cookie : cookies){
        String cookieString = cookie.getName() + " : " + cookie.getValue();
        Log.info(TAG, cookieString);
    }
}