httpclient对象请求时报错javax.net.ssl.SSLException: hostname in certificate didn‘t match

学习httpclient对象请求时出现如下报错:
httpclient对象请求时报错javax.net.ssl.SSLException: hostname in certificate didn‘t match_第1张图片
出现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);
    }
}

运行成功:
httpclient对象请求时报错javax.net.ssl.SSLException: hostname in certificate didn‘t match_第2张图片

你可能感兴趣的:(跳坑——平时遇到的各种小问题)