1
在下面的代碼中,我在網站上運行發佈請求。我不明白爲什麼cookie通過cookiemanager顯示,但它不會顯示在POST標題中。在代碼中查看我的評論。HttpUrlConnection:Cookies在CookieStore中顯示,但不在POST標題中
有人可以解釋我失蹤的東西嗎?
CookieManager cm = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cm);
...
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(urlParams.getBytes(charset));
// Clear cookies to prove they are not from an old request.
cm.getCookieStore().removeAll();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
throw new Exception("Invalid response code.");
// No cookie prints here:
Log.d("Aero", connection.getHeaderFields().toString());
List<HttpCookie> cookies = cm.getCookieStore().getCookies();
for (HttpCookie cookie : cookies) {
if (cookie.getName().equals("ASP.NET_SessionId")) {
// But we do get a cookie here
Log.d("Aero", cookie.toString());
}
}
您是否需要將cookie添加到http標頭中?編輯:看看這裏:http://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager –
@RobbeRoels,是的,這就是我想要做的。但我不能像在你發佈的文章中那樣檢索cookie。他們通過connection.getHeaderFields()獲取cookie。這正是我所做的,但是即使cookiestore顯示實際上存在cookie,代碼也會返回null。 – Reafidy
你想從你的回覆中獲取cookie還是在你的POST中添加一個cookie?因爲connection.getHeaderFields();獲取您回覆的標題欄。使用cm.getCookieStore()。getCookies()(第二部分,「Get Cookies cookieManager並將它們加載到連接」)將它們添加到您的管理器中的POST到服務器。 –