0

尝试从 HttpsURLConnection 读取数据时出现 java.lang.NullPointerException。

HttpsURLConnection.getContent() 为空

此问题仅发生在 4.0 (ICS) 及更高版本上。在 2.0、3.0 等上,代码工作正常。

我在 asyncTask 中进行网络操作。我可能应该提到这是一个小部件。

我已经阅读了很多关于 POST 转向 GET 并更改 setDoOutput 的内容,但这些内容似乎对我没有任何影响。帮助!

08-14 00:18:51.871: D/myWidget(757): http method:POST doOutput:true
08-14 00:18:53.871: D/myWidget(757): dies here. Null:true
08-14 00:18:53.871: W/System.err(757): java.lang.NullPointerException
08-14 00:18:53.871: W/System.err(757):  at com.james.myWidget.Widget.postSSL(Widget.java:587)
08-14 00:18:53.871: W/System.err(757):  at com.james.myWidget.Widget.access$4(Widget.java:540)
08-14 00:18:53.871: W/System.err(757):  at com.james.myWidget.Widget$asyncUpdate.doInBackground(Widget.java:251)
08-14 00:18:53.871: W/System.err(757):  at com.james.myWidget.Widget$asyncUpdate.doInBackground(Widget.java:1)
08-14 00:18:53.871: W/System.err(757):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-14 00:18:53.881: W/System.err(757):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-14 00:18:53.881: W/System.err(757):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-14 00:18:53.881: W/System.err(757):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-14 00:18:53.881: W/System.err(757):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-14 00:18:53.881: W/System.err(757):  at java.lang.Thread.run(Thread.java:856)

这是我的代码,这都在 AsyncTask 的 doInBackground 中。

private Result postSSL(String urlString, String postParams, Cookie cookie){
    debugLog("postSSL: "+urlString);
    try {
        URL url = new URL( urlString );
        HttpURLConnection http = null; 

        if (url.getProtocol().toLowerCase().equals("https")) { 
            trustAllHosts(); 
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); 
            https.setHostnameVerifier(DO_NOT_VERIFY); 
            http = https; 
        } else { 
            http = (HttpURLConnection) url.openConnection(); 
        }

        http.setRequestMethod("POST");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

        http.setUseCaches(false);
        http.setDoInput(true);
        http.setDoOutput(true);

        debugLog("http method:"+http.getRequestMethod()+" doOutput:"+String.valueOf(http.getDoOutput()));

        //Set cookie

        if (cookie.hasCrumbs()){
            //debugLog("postSSL sending cookie :"+cookie.toString());
        http.setRequestProperty("Cookie", cookie.toString());                   
    } 

        //Send request
        if (postParams.length()>0){
            DataOutputStream ostream = new DataOutputStream( http.getOutputStream() );
            ostream.writeBytes(postParams);
            ostream.flush();
            ostream.close();
        }


        //Read response
        Object contents = http.getContent();
        InputStream is = (InputStream) contents;

        StringBuffer responseBuffer = new StringBuffer();
        debugLog("dies here. Null:"+String.valueOf(is==null));
        int c;
        while( ( c = is.read() ) != -1 ) {
            responseBuffer.append( (char) c );
        }
        is.close();        

        //Get the cookie 
    /*String cookie = http.getHeaderField("set-cookie"); 
    if(cookie!=null && cookie.length()>0){ 
        sCookie = cookie;               
    }*/

    // Multi cookie handling:                   
    String responseHeaderName = null;
    for (int i=1; (responseHeaderName = http.getHeaderFieldKey(i))!=null; i++) { 
        if (responseHeaderName.toLowerCase().equals("set-cookie")) {
            cookie.update(http.getHeaderField(i));
            //debugLog("postSSL cookie["+String.valueOf(i)+"] received :"+ http.getHeaderField(i));
        } 
    }

        http.disconnect();
        //debugLog("postSSL cookie received :"+cookie.toString());
        Result res = new Result(responseBuffer.toString(),cookie);
        return res;
    } catch (Exception e){
        e.printStackTrace();
        return new Result("postSSL Exception:"+e.getMessage());
    }
}

要忽略 ssl 证书,我还有:

//SSL Cert workaround

// always verify the host - dont check for certificate 
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { 
    public boolean verify(String hostname, SSLSession session) { 
        return true; 
    } 
}; 

/** 
 * Trust every server - dont check for any certificate 
 */ 
private static void trustAllHosts() { 
        // Create a trust manager that does not validate certificate chains 
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { 
        public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
            return new java.security.cert.X509Certificate[] {}; 
        } 

        public void checkClientTrusted(X509Certificate[] chain, 
            String authType) throws CertificateException { 
        } 

        public void checkServerTrusted(X509Certificate[] chain, 
            String authType) throws CertificateException { 
        } 
        } }; 

        // Install the all-trusting trust manager 
        try { 
        SSLContext sc = SSLContext.getInstance("TLS"); 
        sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 
        } catch (Exception e) { 
        e.printStackTrace(); 
        } 
}
4

0 回答 0