首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >允许AndroidHttpClient中的所有SSL证书

允许AndroidHttpClient中的所有SSL证书
EN

Stack Overflow用户
提问于 2015-07-09 13:33:03
回答 2查看 1.2K关注 0票数 0

我希望你们能帮助我解决这个问题,我做了所有的研究,尝试了我看到的任何东西,但都不能解决我的问题。我想要做的是信任我应用程序中的所有SSL证书。我看到的所有解决方案都是使用URLHttpConnection,但我需要一个适用于AndroidHttpClient的解决方案。请看下面的代码:

代码语言:javascript
复制
AndroidHttpClient httpClient = null;
HttpResponse httpResponse;
Bundle responseBundle;
try{
        httpClient = AndroidHttpClient.newInstance("android");
        httpClient = addCustomCertificate(httpClient);
        httpResponse = httpClient.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            String response = convertStreamToString(instream);
            responseBundle = new Bundle();
            responseBundle.putString("result", response);
            responseBundle.putInt("responseCode", responseCode);
            receiver.send(method, responseBundle);

            instream.close(); 
            httpClient.close();
        }
}

//=

代码语言:javascript
复制
private AndroidHttpClient addCustomCertificate(AndroidHttpClient client)
    {
        SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();

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

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

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

        client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sf, 443));

        return client;
    }

但我总是在日志中捕获的图像中显示错误。我想不出我还能做什么。

EN

回答 2

Stack Overflow用户

发布于 2015-07-09 14:51:16

请检查下面的1,2,3方法,我正在使用它来获取SSSl证书getNewHttpClient,在me.hope中工作良好将会对你有所帮助。

1.Api调用函数,需要通过Asynck Task doInBackground()调用

代码语言:javascript
复制
public String PostConnection(String strUrl,ArrayList<NameValuePair> alstNameValuePair ) {
        Log.d("Stadshart Woerden ","Request URL : "+strUrl);
        Log.d("Stadshart Woerden ","Request Parameters : "+alstNameValuePair.toString());
        InputStream mInputStream = null;
        try {


            HttpClient mHttpClient =  getNewHttpClient();

            HttpPost mHttpPost = new HttpPost(strUrl);

            if(alstNameValuePair!=null)
            { 
                //post the value you want to pass.
                 mHttpPost.setEntity(new UrlEncodedFormEntity(alstNameValuePair));
            }

            //get the value from the server side as response.
            HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            mInputStream = mHttpEntity.getContent();

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

         String strLine = null;
         String strResult = null;

        //convert response in to the string.
        try {
                if(mInputStream!=null){
                  BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
                  StringBuilder mStringBuilder = new StringBuilder();
                  while((strLine = mBufferedReader.readLine()) != null) {
                    mStringBuilder.append(strLine + "\n");
                  }
                      strResult = mStringBuilder.toString();
                      mInputStream.close();
                }
           } 
           catch (Exception e) {
                e.printStackTrace();
            }
         Log.d("Stadshart Woerden ","Response : "+strResult);
         return strResult;
    }

2.

代码语言:javascript
复制
 private 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();
                    }
                }

3.

代码语言:javascript
复制
 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();
            }
        }
票数 1
EN

Stack Overflow用户

发布于 2015-07-09 14:58:38

我将向您展示我的解决方案。但这并不完全是你想要的。我将向您展示如何信任一个服务器(这意味着您已经知道要调用哪个服务器,因此您可以下载它们的证书)。

代码语言:javascript
复制
public static String getConnResponse(String url, String input,
            boolean isGet, boolean isJson) throws IOException {

        if (Constants.SocketFactory == null) {
            CertificateFactory cf;
            try {
                cf = CertificateFactory.getInstance("X.509");
                InputStream caInput = new URL("URL_OF_CERTIFICATE").openStream();
                Certificate ca = cf.generateCertificate(caInput);

                String keyStoreType = KeyStore.getDefaultType();
                KeyStore keyStore = KeyStore.getInstance(keyStoreType);
                keyStore.load(null, null);
                keyStore.setCertificateEntry("ca", ca);

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

                // Create an SSLContext that uses our TrustManager
                SSLContext context = SSLContext.getInstance("TLS");
                context.init(null, tmf.getTrustManagers(), null);
                Constants.SocketFactory = context.getSocketFactory();
            } catch (CertificateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (KeyStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (KeyManagementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        HttpURLConnection conn;
        if (isGet) {
            if (input == null) {
                conn = (HttpURLConnection) new URL(url).openConnection();
            } else {
                conn = (HttpURLConnection) new URL(url + "?" + input)
                .openConnection();
            }

            if (Constants.SocketFactory!=null){
                ((HttpsURLConnection) conn).setSSLSocketFactory(Constants.SocketFactory);
            }
            conn.setRequestProperty("Accept", "application/json,text/html");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Cookie", input);
        } else {
            conn = (HttpURLConnection) new URL(url).openConnection();
            if (Constants.SocketFactory!=null){
                ((HttpsURLConnection) conn).setSSLSocketFactory(Constants.SocketFactory);
            }
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", isJson ? "application/json"
                    : "application/x-www-form-urlencoded");

            OutputStream os = conn.getOutputStream();
            if(input!=null){
                os.write(input.getBytes("UTF-8"));
            }
            os.flush();
            os.close();
        }

        try {
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is,
                    "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            is.close();
            conn.disconnect();
            return sb.toString();
        } catch (SocketException e) {// connection reset
            return null;
        } catch (Exception e) {// connection reset
            return null;
        }
    }

Constants.SocketFactory是一个静态变量,我用它来存储套接字工厂,所以以后我不需要再次下载它。URL_OF_CERTIFICATE是你的证书的url,你可以将它上传到你的云中,你也可以将证书放在你的资产文件夹中,所以你不需要下载它。但这种解决方案的缺点是,下次您想要与不同的服务器通信时,您需要构建一个新的应用程序。我知道这不完全是你所要求的,但我仍然决定把它贴在这里,希望它能给你一些线索,或者可能对其他有类似问题的人有帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31308933

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档