学习httpclient对象请求时出现如下报错:

出现javax.net.ssl.sslexception报错是因为证书不匹配的主机名的问题。
可以在请求的时候多加上表示修改org.apache.http的主机名验证的代码就可以解决
SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
我的原先报错的代码如下:
package com.course.httpclient.demo;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;
import java.io.IOException;
public class MyHttpClient {
@Test
public void test1() throws IOException {
//用来存放我们的结果
String result;
HttpGet get = new HttpGet("https://www.baidu.com/");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
}
}
加上修改org.apache.http的主机名验证解决方法后为:
package com.course.httpclient.demo;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;
import java.io.IOException;
public class MyHttpClient {
@Test
public void test1() throws IOException {
//用来存放我们的结果
String result;
HttpGet get = new HttpGet("https://www.baidu.com/");
HttpClient client = new DefaultHttpClient();
//修改org.apache.http的主机名验证解决问题
SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
HttpResponse response = client.execute(get);
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
}
}
运行成功:

本文介绍了解决使用Apache HttpClient发起HTTPS请求时遇到的SSL证书错误问题,通过修改主机名验证方式,允许所有主机名,成功解决了因证书不匹配主机名导致的javax.net.ssl.SSLException异常。

3020

被折叠的 条评论
为什么被折叠?



