HttpClient中SSLClient证书验证

来源:互联网 发布:网络科技股 编辑:程序博客网 时间:2024/06/07 04:47

在使用HTTPS请求时会出现证书验证问题,通过重新定义X509TrustManager证书管理器可以解决相关问题。

public class SSLClient extends DefaultHttpClient {    public SSLClient() throws Exception{        super();        SSLContext ctx = SSLContext.getInstance("TLS");        X509TrustManager tm = 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;                }        };        ctx.init(null, new TrustManager[]{tm}, null);        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);        ClientConnectionManager ccm = this.getConnectionManager();        SchemeRegistry sr = ccm.getSchemeRegistry();        sr.register(new Scheme("https", 443, ssf));    }}

这个是在声明X509TrustManager的时候重新定义了证书验证方式,从代码即可看出checkClientTrusted,checkServerTrusted这两个证书验证的方法中没有做任何操作,就是对需要验证证书的地方不做操作,已打到通过HTTPS证书验证的目的,后面在HttpClient中的POST方法使用重写过的SSL即可。

public class HttpClientUtil {    public String doPost(String url, Map<String, String> map, String charset) {        HttpClient httpClient = null;        HttpPost httpPost = null;        String result = null;        try {            httpClient = new SSLClient();            httpPost = new HttpPost(url);            //设置参数            List<NameValuePair> list = new ArrayList<NameValuePair>();            Iterator iterator = map.entrySet().iterator();            while (iterator.hasNext()) {                Entry<String, String> elem = (Entry<String, String>) iterator.next();                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));            }            if (list.size() > 0) {                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);                httpPost.setEntity(entity);            }            HttpResponse response = httpClient.execute(httpPost);            if (response != null) {                HttpEntity resEntity = response.getEntity();                if (resEntity != null) {                    result = EntityUtils.toString(resEntity, charset);                }            }        } catch (Exception ex) {            ex.printStackTrace();        }        return result;    }}

代码中创建的SSLClient 就是引用重写之后的SSLClient,这样写有个弊端就是没有对任何证书做校验,因此条用的此方法需要注意网站安全性。
还有一种方法就是导入自己认证的安全证书,在这里不做介绍,可自行百度。

原创粉丝点击