如何使用cookieManager在httpUrlConnection中处理cookie

我有一个服务器请求返回多个cookie,如下所示:

在这里输入图像描述

这就是我将这些cookie存储到cookieManager的方式:

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

这就是我将这些cookie添加到下一个连接的方式:

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

是从cookieManager获取cookie的正确方法吗?我确信有更好的一个…

5 Solutions collect form web for “如何使用cookieManager在httpUrlConnection中处理cookie”

好吧,正确的做法就是这样:

从响应头获取Cookie并将其加载到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获取Cookie并将其加载到连接中:

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

我一直在寻找/尝试几天来解决我的问题:即使login成功后,仍然无法访问受保护的Web资源

我在iOS上创build了相同的应用程序,并没有相同的问题,因为NSUrlConnection在我们后面为我们做了cookie维护。 在Android上,我尝试手动添加cookie

 connection.setRequestProperty("Cookie", "PHPSESSID=str_from_server") 

没有任何运气。

最后我读了这个

并在我的应用程序的开始处添加了以下两行:

 CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); 

现在一切正常。

大卫的回答是最好的。 最容易维护一个本地的CookieManager,并手动写入和从与这个cookiepipe理器关联的cookie存储读取。

此代码将来自响应的Cookie加载到Cookiepipe理器中:

 /** * Gets Cookies from the response header and loads them into cookie manager * * @param conn instance of {@link HttpURLConnection} object * @param cookieManager the cookie manager({@link CookieManager} instance) in which the cookies are to be loaded<p>In case a null object is passed, the function will not perform any action and return back to the caller. </p> */ public static void loadResponseCookies(@Nullable HttpURLConnection conn,@Nullable CookieManager cookieManager) { //do nothing in case a null cokkie manager object is passed if (cookieManager == null || conn == null){ return; } List<String> cookiesHeader = conn.getHeaderFields().get(COOKIES_HEADER); if (cookiesHeader != null) { for (String cookieHeader : cookiesHeader) { List<HttpCookie> cookies; try { cookies = HttpCookie.parse(cookieHeader); } catch (NullPointerException e) { log.warn(MessageFormat.format("{0} -- Null header for the cookie : {1}",conn.getURL().toString(), cookieHeader.toString())); //ignore the Null cookie header and proceed to the next cookie header continue; } if (cookies != null) { Debug("{0} -- Reading Cookies from the response :", conn.getURL().toString()); for (HttpCookie cookie : cookies) { Debug(cookie.toString()); } if (cookies.size() > 0) { cookieManager.getCookieStore().add(null, HttpCookie.parse(cookieHeader).get(0)); } } } } } 

此代码使用与Cookiepipe理器关联的Cookie填充HttpUrlConnection对象:

 public void populateCookieHeaders(HttpURLConnection conn) { if (this.cookieManager != null) { //getting cookies(if any) and manually adding them to the request header List<HttpCookie> cookies = this.cookieManager.getCookieStore().getCookies(); if (cookies != null) { if (cookies.size() > 0) { Debug("{0} -- Adding Cookie Headers : ", url.toString()); for (HttpCookie cookie : cookies) { Debug(cookie.toString(), null); } //adding the cookie header conn.setRequestProperty(COOKIE_REQUEST_HEADER, StringUtils.join(cookies, ";")); } } } } 

这是处理cookie的最安全的线程方式。

我尝试使用一个threadlocal的cookiestore和CookieManager的扩展。 这两种方法都不适用于我的情况。

接受的答案可能有效,但我find了一个更简单的解决scheme。 金拇指的解决scheme在我的情况下不起作用。 看到我的答案连接webView&httpUrlConnection

使用java.net.HttpURLConnection和groovy,只需使用URLConnection#addRequestProperty(String key, String value)添加URLConnection#addRequestProperty(String key, String value)

 import java.net.HttpURLConnection HttpURLConnection createRequest(String chatRequestBody) { HttpURLConnection httpChatRequest = new URL("${endpoint}").openConnection() as HttpURLConnection httpChatRequest.with { doOutput = true requestMethod = 'POST' //headers addRequestProperty("Content-Type", "application/json") addRequestProperty("Client-Platform", "android") //cookies addRequestProperty("Cookie", "cookie_key1=cookie_value1,cookie_key2=cookie_value2") getOutputStream().write(chatRequestBody.getBytes("UTF-8")) } httpChatRequest } 
  • HttpURLConnection发送图像,audio和video文件的参数可能(string或JSONstring)的Android
  • 如何在HttpURLConnection上设置内容types?
  • HttpURLConnection.getResponseCode()在第二次调用时返回-1
  • 如何处理HTTP身份validation使用HttpURLConnection?
  • Android下载二进制文件的问题
  • 连接到需要使用Java进行身份validation的远程URL
  • 从HttpURLConnection对象parsingJSON
  • org.apache.http.entity.FileEntity在Android 6(棉花糖)
  • 使用java.net.URLConnection来触发和处理HTTP请求
  • 如何在Java中发送Https Post请求
  • 为什么你必须调用URLConnection#getInputStream才能写出URLConnection#getOutputStream?