当前位置: 首页 > 面试题库 >

Android SSL HttpGet(无对等证书)错误或(对等连接关闭)错误

范麒
2023-03-14
问题内容

我正在尝试做一个简单的HttpGet来读取网页。我在iOS和Android上通过http(而非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错误。

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

谢谢

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

在尝试以下My-Name-
Is答案后:我已经按照建议创建了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错误:

05-24 08:20:32.500:E / ConnectionHelper(1129):IOException 05-24
08:20:32.550:E / ConnectionHelper(1129):异常加载内容05-24 08:20:32.550:E /
ConnectionHelper(1129) ):javax.net.ssl.SSLException:连接被对等体关闭05-24
08:20:32.550:E /
ConnectionHelper(1129):位于org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(本机方法)
05-24 08:20:32.550:E /
ConnectionHelper(1129):位于org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:410)05-24
08:20:32.550:E /
ConnectionHelper(1129):位于org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl
$ SSLInputStream。(OpenSSLSocketImpl.java:643)05-24 08:20:32.550:E /
ConnectionHelper(1129):位于org.apache。和谐.xnet.provider.jsse.OpenSSLSocketImpl.getInputStream(OpenSSLSocketImpl.java:614)05-24
08:20:32.550:E /
ConnectionHelper(1129):在org.apache.http.impl.io.SocketInputBuffer。(SocketInputBuffer.java:70)05-24
08:20:32.550:E / ConnectionHelper(1129):在org.apache。
http.impl.SocketHttpClientConnection.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)05-24
08:20:32.550:E / ConnectionHelper(1129)
):位于org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:129)05-24
08: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):at
org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)05-24
08:20:32.550:E /
ConnectionHelper(1129):位于org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)05-24
08:20:32.550:E /
ConnectionHelper(1129):在org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)处05-24
08:20:32.550:E /
ConnectionHelper(1129):在org.apache.http.impl.client.AbstractHttpClient处execute(AbstractHttpClient.java:555)05-24
08:20:32.550:E / ConnectionHelper(1129):at
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)处05-24
08:20:32.550:E /
ConnectionHelper(1129):在com.d_apps.my_app.connection_helpers.ConnectionHelper
$ httpGETTask处。 doInBackground(ConnectionHelper.java:114)


问题答案:

以下来源应解决您的问题。

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

}


 类似资料:
  • 如果我在以下URL上运行上述代码:https://eztv.it/shows/887/the-blacklist/,它将按预期工作。两个URL文件大小之间的差异似乎是一个促成因素。在测试同一个服务器的不同URL时,上面的代码似乎只适用于小于30KB的文件。以上任何内容都将生成上述异常。

  • 我有一个问题,集成liquibase maven执行与一个mysql 5.7数据库由Azure作为一个服务.错误日志是: 无法执行目标组织。liquibase:liquibase maven插件:3.0.5:项目上的状态(默认cli)-:设置或运行liquibase:com时出错。mysql。jdbc。例外情况。jdbc4。通信异常:通信链路故障发送到服务器的最后一个数据包是575毫秒前的。握手期

  • 我需要通过HTTPS协议提出请求。我编写了以下代码: 有人知道为什么会这样吗?

  • 我有以下代码: 当我运行代码时,我得到以下异常消息:期间与远程主机的连接失败。 我不知道为什么我会收到这条信息。

  • 我总是在尝试获取https资源时得到相同的错误: 我有一个运行应用程序的自签名虚拟主机,应用程序在上运行良好,但我需要。 我尝试了这个解决方案,但没有成功,也犯了同样的错误 获取所有必需的证书(root和任何中间CA) 使用keytool和BouncyCastle提供程序创建密钥库并导入证书 在android应用程序中加载密钥存储库并使用它进行安全连接不要使用标准java.net.ssl.Http

  • 到目前为止,每当我遇到问题时,我都会使用这个网站,我也找到了解决方案,但这次我甚至不知道发生了什么。 我正在开发一款基于1对1多人模式的游戏。到目前为止,我已经创建了一个服务器和我的客户端程序。 我的服务器为每个与服务器连接的客户端创建一个带有套接字的新线程,当在游戏中按下“新游戏”按钮时,线程会搜索另一个正在寻找新游戏的线程,一旦它找到他,创建一个单独的线程,向两个线程发送消息,向它们发出游戏已