Pregunta

I wrote this AsyncTask for sending small pieces of json through a HttpsURLConnection on an Android Phone. It's not throwing any exceptions in LogCat. But my Node.JS server(HTTPS!) does not receive any requests. What's wrong with this code? Thanks for your response!

    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;
    }

}

Log output:

    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

Solution: I must get the response, even if I don't want it. I added this code after "NetworkCommunication::DataOutputStream" and it worked!

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());
¿Fue útil?

Solución

I suggest you try to get the response from the request (after your "NetworkCommunication::DataOutputStream" flag), and see what it gets. It seems that your app is uploading data to somewhere, question is where?

Also, if you don't need the server response, you may try setting connection.setDoInput(false)

Otros consejos

In my case it was missing internet permission from manifest

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

I think your problem is more relied on the way you do POST json request.

You'll need to use setEntity method to set the HTTP request's header.

Here's a example on Github about how to do GET and POST

For your convenient, I paste the relevant code here:

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]");
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top