Android的SSL HTTPGET(没有同行证书)错误OR(对方将连接关闭)错误Android的

2019-05-13 00:52发布

我试图做一个简单的HTTPGET阅读的网页。 我有这个工作对iOS和通过HTTP在Android上工作,但没有使用https。

网址是内部网络的IP和自定义的端口,这样我就可以使用http像这样使用的路径读取http://ipaddress:port/MyPage.html

HttpClient httpclient = new DefaultHttpClient(httpParameters);
                    HttpResponse response;
        String responseString = null;
        try {
            // Try connection
            HttpGet get = new HttpGet(params[0].path);
            get.addHeader("Authorization",
                    "Basic "
                            + Base64.encodeBytes(new String(params[0].username + ":" + params[0].password)
                                    .getBytes()));
        response = httpclient.execute(get);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else {
            // Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        Log.e(TAG, "ClientProtocolException");
        this.e = e;
    } catch (IOException e) {
        Log.e(TAG, "IOException");
        this.e = e;
    }
    return responseString;

当我尝试使用HTTPS,我得到的No peer certificate错误。 所以我一直使用此代码尝试: HttpClient httpclient = new DefaultHttpClient(httpParameters);

private HttpClient createHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
            HttpProtocolParams.setUseExpectContinue(params, true);

            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schReg.register(new Scheme("https", sf, 8080));
            ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

            return new DefaultHttpClient(conMgr, params);

        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }

但是这给了我一个Connection closed by peer错误。

我究竟做错了什么? 我可以放心地忽略证书,因为这是自签名的证书的内部网络,但我有过VERT和我的应用程序可能有不同的证书的用户无法控制的,所以我真的需要自动接受或绕过它。

谢谢

编辑------------------------------

下面尝试我的名,是回答后:我创建的建议一CustomX509TrustManager类,然后使用它像这样创建一个自定义的HttpClient:

private HttpClient sslClient(HttpClient client) {
        try {
            CustomX509TrustManager tm = new CustomX509TrustManager();
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new MySSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = client.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", ssf, 8080));
            return new DefaultHttpClient(ccm, client.getParams());
        } catch (Exception ex) {
            return null;
        }
    }

最后使用HttpClient的是这样的:

private class httpGETTask extends AsyncTask<GetParams, Void, String> {
private Exception e = null;

@Override
protected String doInBackground(GetParams... params) {
    // Set connection parameters
    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = 15000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    int timeoutSocket = 15000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    Log.v(TAG, params[0].path);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    httpclient = sslClient(httpclient);

    HttpResponse response;
    String responseString = null;
    try {
        // Try connection
        HttpGet get = new HttpGet(params[0].path);
        get.addHeader("Authorization",
                "Basic "
                        + Base64.encodeBytes(new String(params[0].username + ":" + params[0].password)
                                .getBytes()));

        response = httpclient.execute(get);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else {
            // Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        Log.e(TAG, "ClientProtocolException");
        this.e = e;
    } catch (IOException e) {
        Log.e(TAG, "IOException");
        this.e = e;
    }
    return responseString;

记录的路径的格式为https://ipaddress:8080/Page.html ,但我得到一个Connection closed By Peer的错误:

8月5日至24日:20:32.500:E / ConnectionHelper(1129):IOException的8月5日至24日:20:32.550:E / ConnectionHelper(1129):异常加载内容8月5日至24日:20:32.550:E / ConnectionHelper(1129 ):javax.net.ssl.SSLException:20:32.550:连接由对等8月5日至24日关闭E / ConnectionHelper(1129):在org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(本机方法) 8月5日至24日:20:32.550:E / ConnectionHelper(1129):在org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:410)8月5日至24日:20:32.550:E / ConnectionHelper(1129):在org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl $ SSLInputStream(OpenSSLSocketImpl.java:643)八月五日至24日:20:32.550:E / ConnectionHelper(1129):在org.apache。 harmony.xnet.provider.jsse.OpenSSLSocketImpl.getInputStream(OpenSSLSocketImpl.java:614)八月5日至24日:20:32.550:E / ConnectionHelper(1129):在org.apache.http.impl.io.SocketInputBuffer(SocketInputBuffer。的java:70)八月5日至24日:20:32.550:E / ConnectionHelper(1129):在org.apache.http.impl.Soc ketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:83)05-24 08:20:32.550:E / ConnectionHelper(1129):在org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:170)05-24 08:20:32.550:E / ConnectionHelper(1129):在org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:106)8月5日至24日:20:32.550:E / ConnectionHelper(1129):在有机.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:129)8月五日至24日:20:32.550:E / ConnectionHelper(1129):在org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection( DefaultClientConnectionOperator.java:172)05-24 08:20:32.550:E / ConnectionHelper(1129):在org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)05-24 8时20分: 32.550:E / ConnectionHelper(1129):在org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)八月5日至24日:20:32.550:E / ConnectionHelper( 1129):在org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)8月5日至24日:20:32.550:E / ConnectionHelper(1129):在org.apache.http.impl.client .AbstractHttpClient.execute(AbstractHttpClient.java:555)8月5日至24日:20:32.550:E / ConnectionHelper(1129):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)05- 24 08:20:32.550:E / ConnectionHelper(1129):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)8月5日至24日:20:32.550:E / ConnectionHelper(1129) :在com.d_apps.my_app.connection_helpers.ConnectionHelper $ httpGETTask.doInBackground(ConnectionHelper.java:114)

Answer 1:

下面的来源应该解决您的问题。

import android.app.Activity;
import android.widget.EditText;
import android.os.Bundle;
import org.apache.http.HttpResponse;
import org.apache.http.Header
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {

    private EditText text;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (EditText) findViewById(R.id.editText1);
        connect();
    }

    private void connect(){
        try {
            DataLoader dl = new DataLoader();
            String url = "https://IpAddress";
            HttpResponse response = dl.secureLoadData(url); 

            StringBuilder sb = new StringBuilder();
            sb.append("HEADERS:\n\n");

            Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Header h = headers[i];
                sb.append(h.getName()).append(":\t").append(h.getValue()).append("\n");
            }

            InputStream is = response.getEntity().getContent();
            StringBuilder out = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            for (String line = br.readLine(); line != null; line = br.readLine())
                out.append(line);
            br.close();

            sb.append("\n\nCONTENT:\n\n").append(out.toString()); 

            Log.i("response", sb.toString());
            text.setText(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}


import android.app.Application;
import android.content.Context;
import java.io.InputStream;
public class MeaApplication extends Application {

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        MeaApplication.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MeaApplication.context;
    }

    public static InputStream loadCertAsInputStream() {
        return MeaApplication.context.getResources().openRawResource(
                R.raw.meacert);
    }

}


import org.apache.http.conn.ssl.SSLSocketFactory;
import javax.net.ssl.SSLContext;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.UnrecoverableKeyException;
import javax.net.ssl.TrustManager;
import java.net.Socket;
import java.io.IOException;
import java.net.UnknownHostException;
/**
 * Taken from: http://janis.peisenieks.lv/en/76/english-making-an-ssl-connection-via-android/
 *
 */
public class CustomSSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public CustomSSLSocketFactory(KeyStore truststore)
            throws NoSuchAlgorithmException, KeyManagementException,
            KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new CustomX509TrustManager();

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    public CustomSSLSocketFactory(SSLContext context)
            throws KeyManagementException, NoSuchAlgorithmException,
            KeyStoreException, UnrecoverableKeyException {
        super(null);
        sslContext = context;
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port,
            boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port,
                autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}


import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
public class CustomX509TrustManager implements X509TrustManager {

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

    @Override
    public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
            String authType) throws CertificateException {

        // Here you can verify the servers certificate. (e.g. against one which is stored on mobile device)

        // InputStream inStream = null;
        // try {
        // inStream = MeaApplication.loadCertAsInputStream();
        // CertificateFactory cf = CertificateFactory.getInstance("X.509");
        // X509Certificate ca = (X509Certificate)
        // cf.generateCertificate(inStream);
        // inStream.close();
        //
        // for (X509Certificate cert : certs) {
        // // Verifing by public key
        // cert.verify(ca.getPublicKey());
        // }
        // } catch (Exception e) {
        // throw new IllegalArgumentException("Untrusted Certificate!");
        // } finally {
        // try {
        // inStream.close();
        // } catch (IOException e) {
        // e.printStackTrace();
        // }
        // }
    }

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }

}


import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyManagementException;
import java.net.URISyntaxException;
import java.security.KeyStoreException;
import java.security.UnrecoverableKeyException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.security.SecureRandom;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.client.methods.HttpGet;
public class DataLoader {

    public HttpResponse secureLoadData(String url)
            throws ClientProtocolException, IOException,
            NoSuchAlgorithmException, KeyManagementException,
            URISyntaxException, KeyStoreException, UnrecoverableKeyException {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { new CustomX509TrustManager() },
                new SecureRandom());

        HttpClient client = new DefaultHttpClient();

        SSLSocketFactory ssf = new CustomSSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = client.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        DefaultHttpClient sslClient = new DefaultHttpClient(ccm,
                client.getParams());

        HttpGet get = new HttpGet(new URI(url));
        HttpResponse response = sslClient.execute(get);

        return response;
    }

}


Answer 2:

如果使用的是“不受信任”(开发商)证书,然后下面是解决方案。 我们需要信任所有证书,以下是做到这一点的方式。 对于受信任的证书它的工作原理不增加以下功能,我们只是我们需要改变HTTP到HTTPS,它会工作。

这里是不信任的证书的解决方案。

在HttpClient的方式,你应该创建org.apache.http.conn.ssl.SSLSocketFactory,而不是一个org.apache.http.conn.ssl.SSLSocketFactory本身的自定义类

例如像...

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;
public class MySSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

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

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}

并同时创造HttpClient的实例使用这个类。

public HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}


Answer 3:

检查设备的日期。 你可能已经把它改成一个不同的一年。 当孩子们用我的手机我经常得到这个问题。



Answer 4:

如果你有一个受信任的证书访问服务器更好solutionis正确配置SSL,因为Android是更受限制的是iOS和桌面浏览器关于SSL验证

这个解决方案并不需要在Android应用的任何变化,所以它更干净。

下面是Apache的一个例子SSL配置(将其添加到您的虚拟主机定义,例如,在/ etc / apache2的/网站启用)

SSLEngine on
SSLCertificateFile    YOUR_CERT_PATH
SSLCACertificateFile  CA_ROOT_CERT_PATH
SSLCertificateKeyFile KEY_PATH

我有同样的错误,当我加入了CA根证书,去和android的错误没有了抱怨。 提供正确的路径,这些文件,重新启动Apache并再次测试。

该文件的CA根认证证书可以包含根和中间证书

你可以测试你的SSL配置这个网站 ,并确保在根据该服务器发送所有需要的证书认证路径的结果。



Answer 5:

当此异常搜索,你得到的是实行“允许所有证书”的建议。

对于SSLPeerUnverifiedException的Javadoc指出:

当对等无法识别其自身(例如,没有证书,特定的加密套件正在使用不支持认证,或SSL握手期间没有建立对等体认证)该引发异常。

因此,错误可能是连接是如此不稳定/不稳定,并要求采取荒谬的时间量。 在我们的移动应用程序,我们有时会遇到连接/编程超时的很多公司在与这些SSLPeerUnverifiedException组合。 有些请求打通而是采取60 + - 网络连接简单地吮吸超越在这些情况下,所有的手段。

简单地用暴力迫使这个“允许所有证书”是不是在这种情况下,可取的 - 而实现适当的重试策略。



Answer 6:

允许Android的安全性提供者来开始你的应用程序时更新。

5.0+之前默认的提供不会禁用SSLv3的。 只要你有访问谷歌Play服务,它是相对简单的,从您的应用程序补丁Android的安全性提供者。

  private void updateAndroidSecurityProvider(Activity callingActivity) {
    try {
        ProviderInstaller.installIfNeeded(this);
    } catch (GooglePlayServicesRepairableException e) {
      // Thrown when Google Play Services is not installed, up-to-date, or  enabled
        // Show dialog to allow users to install, update, or otherwise    enable Google Play services.
       GooglePlayServicesUtil.getErrorDialog(e.getConnectionStatusCode(), callingActivity, 0);
    } catch (GooglePlayServicesNotAvailableException e) {
        Log.e("SecurityException", "Google Play Services not available.");
    }
}

来源: 修补安全提供ProviderInstaller提供商



Answer 7:

我本来使用HttpsURLConnection ,但让我决定去与它不持续工作HttpClient 。 它现在。



文章来源: Android SSL HttpGet (No peer certificate) error OR (Connection closed by peer) error