Android - HttpsURLConnection无效

时间:2013-11-01 14:51:32

标签: android sockets https httpsurlconnection

我写了这个AsyncTask,用于通过Android手机上的HttpsURLConnection发送小块json。它不会在LogCat中抛出任何异常。但是我的Node.JS服务器(HTTPS!)没有收到任何请求。这段代码出了什么问题?谢谢你的回复!

    private class NetworkCommunication extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String paramUrl = params[0];
        String paramRequest = params[1];

        HttpsURLConnection connection = null;

        TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };

        try {
            SSLContext sslcontext = SSLContext.getInstance("SSL");
            sslcontext.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
            Log.d("meet", "NetworkCommunication::setDefaultSSLSocketFactory()");

            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

            });
            Log.d("meet", "NetworkCommunication::setDefaultHostnameVerifier()");

            URL url = new URL(paramUrl);                
            connection = (HttpsURLConnection) url.openConnection();
            Log.d("meet", "NetworkCommunication::openConnection()");

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Content-Length", String.valueOf(paramRequest.getBytes().length));
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            Log.d("meet", "NetworkCommunication::set...()");

            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(paramRequest);
            output.flush();
            output.close();
            Log.d("meet", "NetworkCommunication::DataOutputStream");


        } catch (Exception e) {
            Log.d("meet", "NetworkCommunication::Exception", e);
            return null;
        } finally {
            if(connection != null)
                connection.disconnect();
        }

        return null;
    }

}

日志输出:

    11-01 16:14:10.595: D/dalvikvm(4265): GC_CONCURRENT freed 199K, 14% free 9660K/11143K, paused 14ms+2ms, total 39ms
11-01 16:14:10.595: D/dalvikvm(4265): WAIT_FOR_CONCURRENT_GC blocked 9ms
11-01 16:14:10.715: D/dalvikvm(4265): GC_CONCURRENT freed 277K, 14% free 9889K/11463K, paused 12ms+12ms, total 39ms
11-01 16:14:10.775: D/dalvikvm(4265): GC_CONCURRENT freed 313K, 14% free 10121K/11719K, paused 2ms+2ms, total 27ms
11-01 16:14:10.775: D/dalvikvm(4265): WAIT_FOR_CONCURRENT_GC blocked 9ms
11-01 16:14:10.780: D/dalvikvm(4265): WAIT_FOR_CONCURRENT_GC blocked 12ms
11-01 16:14:10.790: D/AbsListView(4265): Get MotionRecognitionManager
11-01 16:14:10.835: D/dalvikvm(4265): GC_CONCURRENT freed 251K, 13% free 10431K/11975K, paused 2ms+5ms, total 23ms
11-01 16:14:10.840: D/meet(4265): NetworkCommunication::setDefaultSSLSocketFactory()
11-01 16:14:10.840: E/GooglePlayServicesUtil(4265): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
11-01 16:14:10.845: D/meet(4265): NetworkCommunication::setDefaultHostnameVerifier()
11-01 16:14:10.845: D/meet(4265): NetworkCommunication::openConnection()
11-01 16:14:10.845: D/meet(4265): NetworkCommunication::set...()
11-01 16:14:10.890: D/libEGL(4265): loaded /system/lib/egl/libEGL_mali.so
11-01 16:14:10.890: D/libEGL(4265): loaded /system/lib/egl/libGLESv1_CM_mali.so
11-01 16:14:10.895: D/libEGL(4265): loaded /system/lib/egl/libGLESv2_mali.so
11-01 16:14:10.895: D/(4265): Device driver API match
11-01 16:14:10.895: D/(4265): Device driver API version: 10
11-01 16:14:10.895: D/(4265): User space API version: 10 
11-01 16:14:10.895: D/(4265): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Thu Oct 25 08:43:05 KST 2012 
11-01 16:14:10.915: D/OpenGLRenderer(4265): Enabling debug mode 0
11-01 16:14:10.980: D/dalvikvm(4265): GC_FOR_ALLOC freed 245K, 15% free 10487K/12231K, paused 18ms, total 18ms
11-01 16:14:11.025: D/dalvikvm(4265): GC_FOR_ALLOC freed 154K, 15% free 10486K/12231K, paused 28ms, total 29ms
11-01 16:14:11.045: D/dalvikvm(4265): GC_FOR_ALLOC freed 152K, 15% free 10487K/12231K, paused 17ms, total 18ms
11-01 16:14:11.065: D/dalvikvm(4265): GC_FOR_ALLOC freed 152K, 15% free 10486K/12231K, paused 17ms, total 18ms
11-01 16:14:11.100: D/dalvikvm(4265): GC_FOR_ALLOC freed 178K, 15% free 10504K/12231K, paused 27ms, total 27ms
11-01 16:14:11.135: D/dalvikvm(4265): GC_FOR_ALLOC freed 157K, 15% free 10514K/12231K, paused 27ms, total 27ms
11-01 16:14:11.160: D/dalvikvm(4265): GC_FOR_ALLOC freed 169K, 15% free 10519K/12231K, paused 17ms, total 18ms
11-01 16:14:11.180: D/dalvikvm(4265): GC_FOR_ALLOC freed 152K, 15% free 10519K/12231K, paused 17ms, total 18ms
11-01 16:14:11.285: D/dalvikvm(4265): GC_CONCURRENT freed 384K, 15% free 10573K/12295K, paused 22ms+13ms, total 65ms
11-01 16:14:11.285: D/dalvikvm(4265): WAIT_FOR_CONCURRENT_GC blocked 42ms
11-01 16:14:11.385: D/dalvikvm(4265): GC_CONCURRENT freed 184K, 13% free 10902K/12423K, paused 12ms+13ms, total 54ms
11-01 16:14:11.445: D/meet(4265): NetworkCommunication::DataOutputStream
11-01 16:14:11.485: D/dalvikvm(4265): GC_CONCURRENT freed 231K, 12% free 11228K/12743K, paused 12ms+2ms, total 32ms
11-01 16:14:11.485: D/dalvikvm(4265): WAIT_FOR_CONCURRENT_GC blocked 6ms
11-01 16:14:11.485: D/dalvikvm(4265): WAIT_FOR_CONCURRENT_GC blocked 6ms
11-01 16:14:11.490: D/dalvikvm(4265): WAIT_FOR_CONCURRENT_GC blocked 7ms
11-01 16:14:11.490: D/dalvikvm(4265): WAIT_FOR_CONCURRENT_GC blocked 12ms
11-01 16:14:11.555: D/dalvikvm(4265): GC_CONCURRENT freed 469K, 14% free 11399K/13191K, paused 2ms+5ms, total 28ms

解决方案: 我必须得到回应,即使我不想要它。我在“NetworkCommunication :: DataOutputStream”之后添加了这段代码并且它有效!

InputStream istream = connection.getInputStream();
            BufferedReader input = new BufferedReader(new InputStreamReader(istream));
            String line;
            StringBuffer response = new StringBuffer();

            while((line = input.readLine()) != null) {
                response.append(line);
                response.append('\n');
            }               
            Log.d("meet", "NetworkCommunication::response=" + response.toString());

3 个答案:

答案 0 :(得分:2)

我建议您尝试从请求中获取响应(在“NetworkCommunication :: DataOutputStream”标志之后),并查看它的内容。您的应用似乎正在将数据上传到某个地方,问题在哪里?

此外,如果您不需要服务器响应,可以尝试设置connection.setDoInput(false)

答案 1 :(得分:0)

在我的情况下,它缺少来自清单的互联网许可

 <uses-permission android:name="android.permission.INTERNET" />

答案 2 :(得分:0)

我认为你的问题更依赖于POST json请求的方式。

您需要使用setEntity方法设置HTTP请求的标头。

以下是关于如何GETPOST

example on Github

为方便起见,我在此处粘贴相关代码:

DefaultHttpClient httpclient = new DefaultHttpClient();
                        HttpPost httpPostRequest = new HttpPost(URL);

                        StringEntity se;
                        se = new StringEntity(jsonObjSend.toString());

                        // Set HTTP parameters
                        httpPostRequest.setEntity(se);
                        httpPostRequest.setHeader("Accept", "application/json");
                        httpPostRequest.setHeader("Content-type", "application/json");
                        httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

                        long t = System.currentTimeMillis();
                        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
                        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");