【问题标题】:Android - HttpsURLConnection not workingAndroid - HttpsURLConnection 不工作
【发布时间】:2013-11-12 19:07:57
【问题描述】:

我编写了这个 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());

【问题讨论】:

  • 任何日志?调试方面,你走了多远?
  • 您好 njzk2,感谢您的快速回复。我不知道你的意思,但我在代码下附加了日志文件。
  • 我建议您尝试从请求中获取响应(在您的“NetworkCommunication::DataOutputStream”标志之后),看看它会得到什么。您的应用似乎正在将数据上传到某个地方,问题是在哪里?
  • 它有效。我必须得到回应(无论我是否需要)。请发表您的评论,以便我可以接受它作为答案,我将在问题中更新我的代码。谢谢!

标签: android sockets https httpsurlconnection


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我认为您的问题更多地取决于您执行POST json 请求的方式。

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

    这里有一个example on GithubGETPOST 的操作方法

    为了方便,我把相关代码贴在这里:

    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]");
    

    【讨论】:

    • 谢谢!但这不适用于 HTTPS,不是吗?
    • setEntity 用于 HttpClient。 SO 正在使用 HttpURLConnection
    • @raptor 抱歉,我没有仔细检查您的问题。我的回答不适合你的问题。
    【解决方案3】:

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

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

    【讨论】:

    • NO,如果作者没有设置所需的权限,日志猫会给出异常
    猜你喜欢
    • 2013-03-02
    • 2014-06-11
    • 2016-11-05
    • 1970-01-01
    • 2016-01-31
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    相关资源
    最近更新 更多