- 这已经解决,见帖子的底部 -
我正在尝试从已建立的连接中获取cookie。以下代码运行良好,但它在Android 2.2及更低版本上抛出了NullPointer异常:
URL url = new URL("https://myloginform");
trustAllHosts(); //because the certificate is not singed
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(DO_NOT_VERIFY);
conn.setInstanceFollowRedirects(false);
conn.setDoOutput(true);
//Connect to login-page and send login data
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
//get cookies THIS WORKS ONLY ON ANDROID 2.3 AND ABOVE
List<String> cookies = conn.getHeaderFields().get("Set-Cookie");
conn.disconnect();
//connect to overview page
url = new URL("https://mynextpage");
trustAllHosts();
conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(DO_NOT_VERIFY);
conn.setInstanceFollowRedirects(false);
//Send cookies for identification - THIS WILL THROW A NULLPOINTER EXCEPTION
for (String cookie : cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while (!(line2.contains("</html>"))) {
line = rd.readLine();
line2 += line;
}
// wr.close();
rd.close();
有谁知道为什么?
找到解决方案。 Android 2.2中没有“Set-Cookie”,它是“set-cookie”
答案 0 :(得分:0)
这不是Android的东西,它是一个HTTP的东西。 Cookie的HTTP标头为Set-Cookie
。也许Android 2.3+的行为很奇怪,但在HTTP请求/响应中不应该修改标头。你应该把它归档为bug。