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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习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);
    }
}

运行成功:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值