java在使用htppclient 获取https网站内容时。会发生错误,解决方案很多,比如导入证书等。
发现了一个简单的方法,不需要导入证书,也可以实现。
是用的是 apache http 的jar包。具体代码如下:
写一个类,继承 DefaultHttpClient ,这个类也可以写成内部类。
class HttpsClient 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));
}
}
以后的代码就可和以前获取http网站的内容一样了,唯一不同的地方是
将 HttpClient httpClient = new DefaultHttpClient(); 改为 : HttpClient httpClient = new HttpsClient();
完整代码如下:
String url = "https://......";
HttpClient httpClient = new HttpsClient();
HttpPost httpPost= new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
String content = sb.toString();
比较网上的各种解决方案,这个算是最简单,代码也是最少的了。