java - 尝试 sslException 时套接字已关闭异常

标签 java android ssl

我正在尝试在 Android 客户端上使用自定义证书实现 SSL 连接。如果我尝试使用我编写的普通 Java 程序连接到同一台服务器(我在其中使用系统参数导入 keystore ),一切正常。此外,如果我使用 android 方法连接到服务器,但没有 https,它工作正常。但是一旦我使用带 https 的 Android 方法(使用如下所示的方法),它就会给我这个错误:

04-06 20:12:29.234: W/System.err(2328): java.net.SocketException: Socket is closed
04-06 20:12:29.234: W/System.err(2328):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.checkOpen(OpenSSLSocketImpl.java:237)
04-06 20:12:29.234: W/System.err(2328):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:250)
04-06 20:12:29.234: W/System.err(2328):     at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
04-06 20:12:29.234: W/System.err(2328):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
04-06 20:12:29.234: W/System.err(2328):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:442)
04-06 20:12:29.244: W/System.err(2328):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
04-06 20:12:29.244: W/System.err(2328):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
04-06 20:12:29.244: W/System.err(2328):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
04-06 20:12:29.244: W/System.err(2328):     at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
04-06 20:12:29.244: W/System.err(2328):     at libcore.net.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:281)
04-06 20:12:29.244: W/System.err(2328):     at john.z.lead.utils.ServerRequest.get_response(ServerRequest.java:497)
04-06 20:12:29.244: W/System.err(2328):     at john.z.lead.utils.ServerRequest.logout(ServerRequest.java:797)
04-06 20:12:29.244: W/System.err(2328):     at john.z.lead.fragments.Logout_Fragment$1$1.run(Logout_Fragment.java:59)
04-06 20:12:29.244: W/System.err(2328):     at java.lang.Thread.run(Thread.java:841)

我使用的代码是:

public static JSONObject get_response(List<Parameter> params,
        final String address) throws IOException, JSONException, LeadException {
    // String body = "param1=" + URLEncoder.encode( "value1", "UTF-8" ) +
    // "&" +
    // "param2=" + URLEncoder.encode( "value2", "UTF-8" );

    StringBuilder body = new StringBuilder();
    for (Parameter pa : params) {
        body.append(pa.getKey() + "="
                + URLEncoder.encode(pa.getValue(), "UTF-8") + "&");
    }
    try {

        URL url = new URL(address);

        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        if (connection instanceof HttpsURLConnection) {
            KeyStore trusted = KeyStore.getInstance("BKS");

            // Get the raw resource, which contains the keystore with
            // your trusted certificates (root and any intermediate certs)
            InputStream in = Datastore.getActiv().getResources()
                    .openRawResource(R.raw.truststore);
            // Initialize the keystore with the provided trusted
            // certificates
            // Also provide the password of the keystore
            trusted.load(in, "lead".toCharArray());

            // Create a TrustManager that trusts the CAs in our KeyStore
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(trusted);



            // Create an SSLContext that uses our TrustManager
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);


            ((HttpsURLConnection) connection)
                    .setSSLSocketFactory(context.getSocketFactory());

        }
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length",
                String.valueOf(body.length()));
        OutputStreamWriter writer = new OutputStreamWriter(
                connection.getOutputStream());

        writer.write(body.toString());
        writer.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));

        StringBuilder build = new StringBuilder();
        for (String line; (line = reader.readLine()) != null;) {
            build.append(line);
        }

        writer.close();
        reader.close();

        return new JSONObject(build.toString());

    } catch (UnknownHostException | FileNotFoundException
            | ConnectException e) {
        Datastore.getActiv().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(
                        Datastore.getActiv(),
                        "Konnte keine Verbindung zum Server ( "
                                + address
                                + " ) herstellen.\nBitte überprüfen Sie ihre Netzwerkverbindung und / oder\nkontaktieren Sie einen Administrator",
                        Toast.LENGTH_LONG).show();
                ;

            }

        });
        throw e;
    } catch (KeyManagementException|KeyStoreException|NoSuchAlgorithmException|CertificateException e) {
        MessageDialog.showMessageDialog(Datastore.getActiv(), "Es ist ein kritischer Fehler beim Herstellen der sicheren Verbindung aufgetreten");
        e.printStackTrace();
        throw new LeadException(LeadException.Errorcode.UNKNOWN);
    } 

}

最佳答案

SocketException: socket is closed 表示关闭了套接字然后继续使用它。

注意您不需要设置Content-Length header 。 HttpURLConnection 会自动为您完成。

关于java - 尝试 sslException 时套接字已关闭异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29481699/

相关文章:

java - 使用 Eclipse 防止将文件提交到 SVN 并发出警告

java - 使用 Apache cxf 的 Dispatch api 时 SOAP Action 为空

Android Camera2 onCaptureStarted 回调

wordpress - http 运行良好。但是 https 不工作并重定向到其他域

java - Eclipse [桌面 headless ]

android - OpenGL ES 2.0 中具有不同纹理坐标的两个纹理

android - 用Cordova显示本地保存的图片

ssl - Opencart 链接不是 https?

perl - 为什么我不能使用 Perl 的 AuthCAS 连接到我的 CAS 服务器?

java - 无法加载Spring Web应用程序的ApplicationContext