忽略DefaultHttpClient中的ssl错误

时间:2011-08-29 12:14:09

标签: android ssl

我正在寻找忽略默认httpclient中所有ssl错误(例如,不信任)的可能性。我在这里看到了很多解决方案,但我必须导入一个特定的证书,并将其添加到trustmanager,或者它是用于DefaultHttpClient的HttpsUrlConnection instad。 我用过的webrequests是:

    public static String makeGETRequest(String s,String encoding)
{
    DefaultHttpClient http = new DefaultHttpClient();
    final String username = "USERNAME";
    final String password = "PASSWORD";
    UsernamePasswordCredentials c = new UsernamePasswordCredentials(username,password);
    BasicCredentialsProvider cP = new BasicCredentialsProvider(); 
    cP.setCredentials(AuthScope.ANY, c); 
    http.setCredentialsProvider(cP);
    HttpResponse res;
    try {

        res = http.execute(new HttpGet(s));
        InputStream is = res.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while((current = bis.read()) != -1){
              baf.append((byte)current);
         }

        return  new String(baf.toByteArray(),encoding);
       } 
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        return "error: " + e.getMessage();
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        return "error: " + e.getMessage();
    } 

}

public static String makePOSTRequest(String s, List <NameValuePair> nvps,String encoding)
{
    DefaultHttpClient http = new DefaultHttpClient();
    final String username = "USERNAME";
    final String password = "PASSWORD";
    UsernamePasswordCredentials c = new UsernamePasswordCredentials(username,password);
    BasicCredentialsProvider cP = new BasicCredentialsProvider(); 
    cP.setCredentials(AuthScope.ANY, c); 
    http.setCredentialsProvider(cP);
    HttpResponse res;
    try {
        HttpPost httpost = new HttpPost(s);
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.DEFAULT_CONTENT_CHARSET));
        res = http.execute(httpost);
        InputStream is = res.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while((current = bis.read()) != -1){
              baf.append((byte)current);
         }
        res = null;
        httpost = null;
        String ret = new String(baf.toByteArray(),encoding);
        return  ret;
       } 
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        return e.getMessage();
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        return e.getMessage();
    } 

}

有没有人知道如何忽略此代码中的ssl错误?

编辑: 因为我只需要信任一个特定的(过期的)证书,我尝试以下列方式覆盖DefaultHttpClient:

public class MyHttpClient extends DefaultHttpClient {
final Context context;

  public MyHttpClient(Context context) {
    this.context = context;
  }

  @Override protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(
        new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", newSslSocketFactory(), 443));
    return new SingleClientConnManager(getParams(), registry);
  }

  private SSLSocketFactory newSslSocketFactory() {
    try {
      KeyStore trusted = KeyStore.getInstance("BKS");
      InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
      try {
        trusted.load(in, "mypassword".toCharArray());
      } finally {
        in.close();
      }
      return new SSLSocketFactory(trusted);
    } catch (Exception e) {
      throw new AssertionError(e);
    }
  }

}

R.raw.mykeystore中的文件是一个.bks文件,我用Portecle创建,我创建了一个新的bks并导入了过期证书的存储的pem,它看起来很有用,密钥存储是加载没有错误,但如果我执行请求,我得到一个IO异常,消息“没有对等证书”,可能是什么问题?

1 个答案:

答案 0 :(得分:11)

我解决了这个问题。如果您使用上述请求,它可以工作,但使用您自己的版本而不是DefaultHttpClient:

public class MyHttpClient extends DefaultHttpClient {
final Context context;
TrustManager easyTrustManager = new X509TrustManager() {
    @Override
    public void checkClientTrusted(
            X509Certificate[] chain,
            String authType) throws CertificateException {
    }

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

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }    
};
  public MyHttpClient(Context context) {
    this.context = context;
  }

  @Override protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(
        new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", newSslSocketFactory(), 443));
    return new SingleClientConnManager(getParams(), registry);
  }


  private MySSLSocketFactory newSslSocketFactory() {
    try {
      KeyStore trusted = KeyStore.getInstance("BKS");      
      try {
         trusted.load(null, null);

      } finally {
      }

      MySSLSocketFactory sslfactory =  new MySSLSocketFactory(trusted);
        sslfactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return sslfactory;
    } catch (Exception e) {
      throw new AssertionError(e);
    }

  }
  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();
        }
    }
   }
相关问题