如何使用cookieManager处理cookie中的HttpURLConnection [英] How to handle cookies in httpUrlConnection using cookieManager

查看:218
本文介绍了如何使用cookieManager处理cookie中的HttpURLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回多个cookie的服务器请求,这样的:

I have a server request that returns multiple cookies, like that:

这是我如何存储这些饼干的cookieManager:

This is how I'm storing these cookies to the cookieManager:

HttpURLConnection connection = ... ;
static java.net.CookieManager msCookieManager = new java.net.CookieManager();
msCookieManager.put(COOKIES_URI, connection.getHeaderFields());

这是我如何将这些cookie到下一个连接:

This is how I'm adding these cookies to the next connection:

connection.setRequestProperty("Cookie", 
  msCookieManager.getCookieStore().get(COOKIES_URI).toString());

这是不是正确的方式来从cookieManager饼干? 我敢肯定有一个更好的......

Is it the right way to get the cookies from the cookieManager?, I'm quite sure there is a better one...

推荐答案

好了,以正确的方式来做到这一点是一样的:

Ok, the right way to do it is just like that:

获取饼干形式的响应报头,并将其加载到cookieManager:

static final String COOKIES_HEADER = "Set-Cookie";
HttpURLConnection connection = ... ;
static java.net.CookieManager msCookieManager = new java.net.CookieManager();

Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

if(cookiesHeader != null)
{
    for (String cookie : cookiesHeader) 
    {
      msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));
    }               
}

获取饼干形成cookieManager,并将它们加载到连接:

if(msCookieManager.getCookieStore().getCookies().size() > 0)
{
    //While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
    connection.setRequestProperty("Cookie",
    TextUtils.join(";",  msCookieManager.getCookieStore().getCookies()));    
}

这篇关于如何使用cookieManager处理cookie中的HttpURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆