Android 2.2上Cookie的NullPointer异常-适用于2.3及以上版本



这已经解决了,请参阅post-的底部

我正试图从已建立的连接中获取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中没有"设置Cookie",它是"设置Cookie"

这不是Android的事情,而是HTTP的事情。Cookie的HTTP标头为Set-Cookie。也许Android 2.3+的行为很奇怪,但不应该修改HTTP请求/响应中的标头。您应该将其作为bug进行归档。

最新更新