Android BasicCookieStore, Cookies and HttpGet

偶尔善良 提交于 2019-12-11 05:59:18

问题


I have a an app that should send a GET request to a URL and send some cookies along with it. I've been looking at a few code examples for BasicCookieStore and Cookie classes, but I'm not able to figure out how to use them. Can anyone point me in the right direction?


回答1:


To use cookies you need something along the lines of:

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);

And if you want to keep cookies between requests, you have to reuse cookieStore and ctx for every request.

Also, you may read your cookieStore to see what's inside:

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


来源:https://stackoverflow.com/questions/13556712/android-basiccookiestore-cookies-and-httpget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!