如何使用cookieManager处理cookie中的HttpURLConnection如何使用、cookieManager、HttpURLConnection、cookie

2023-09-12 08:52:37 作者:像個笑話

我有一个返回多个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()));    
}