解决Java中https请求接口报错问题

1. 解决SSLException: Certificate for <域名> doesn't match any of the subject alternative报错问题

1.1 问题描述

最近在做一个智能问答客服项目,对接的是云问接口,然后云问接口对接使用的是https方式,之前一直是http方式,突然的改变,使得项目访问报错。报错信息如标题所示。就是SSL证书的问题。

1.2 解决方案

第一种解决方案:

遇到问题首先debug一下,发现是在项目中的一个工具类中引起的报错,好像是因为没有规定使用默认证书之类的吧,不知道理解的对不对,反正根据下面的代码改了之后就可以了,但是还是会有一些其它的问题,具体可以往下看。

在之前的代码上,也就是发送http请求的代码那里,增加下面两条语句。作用主要是配置带有SSL/TSL安全连接的HttpClient。

java 复制代码
SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE);
httpclient = HttpClients.custom().setSSLSocketFactory(scsf).build();

修正之后的代码如下:

java 复制代码
public static String doGet(String url, Map<String, Object> params) throws IOException {  
        String apiUrl = url;  
        StringBuffer param = new StringBuffer();  
        int i = 0;  
        for (String key : params.keySet()) {  
            if (i == 0)  
                param.append("?");  
            else  
                param.append("&");  
            param.append(key).append("=").append(params.get(key));  
            i++;  
        }  
        apiUrl += param;  
        String result = null;  
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE);
            httpclient = HttpClients.custom().setSSLSocketFactory(scsf).build();

            HttpGet httpPost = new HttpGet(apiUrl);  
            HttpResponse response = httpclient.execute(httpPost);

            HttpEntity entity = response.getEntity();  
            if (entity != null) {  
                InputStream instream = entity.getContent();  
                result = IOUtils.toString(instream, "UTF-8");  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        } finally {
        	if(httpclient!=null) {
        		httpclient.close();
        	}
        }
        return result;  
    }  

第二种解决方案:

这种解决方案是ChatGPT给的,我没有验证其正确性。

java 复制代码
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class HTTPSRequestExample {
    public static void main(String[] args) {
        try {
            // 创建自定义SSLContext
            SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial((chain, authType) -> true).build();

            // 创建SSLConnectionSocketFactory并禁用主机名验证
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

            // 使用自定义SSLConnectionSocketFactory创建HttpClient
            CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();

            // 创建要发送的GET请求
            HttpGet request = new HttpGet("https://example.com");

            // 发送请求并获取响应
            CloseableHttpResponse response = httpClient.execute(request);

            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line;
            StringBuilder content = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }

            // 输出响应内容
            System.out.println("Response Content: " + content.toString());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
    }
}

1.3 参考文献

stackoverflow参考文档

CSDN参考文档

2. 出现新问题

根据上面的修改代码后,又会出现新的问题,图片,音频,视频似乎不行,f12看控制台会有报错,好像是与证书相关的报错,同时也会改变请求的路径为本地路径。如下图所示的报错。

相关推荐
_Chipen18 分钟前
C++基础问题
开发语言·c++
天河归来1 小时前
springboot框架redis开启管道批量写入数据
java·spring boot·redis
止观止1 小时前
JavaScript对象创建9大核心技术解析
开发语言·javascript·ecmascript
张先shen1 小时前
Elasticsearch RESTful API入门:全文搜索实战
java·大数据·elasticsearch·搜索引擎·全文检索·restful
codervibe1 小时前
如何用 Spring Security 构建无状态权限控制系统(含角色菜单控制)
java·后端
codervibe1 小时前
项目中如何用策略模式实现多角色登录解耦?(附实战代码)
java·后端
TCChzp1 小时前
synchronized全链路解析:从字节码到JVM内核的锁实现与升级策略
java·jvm
大葱白菜1 小时前
🧩 Java 枚举详解:从基础到实战,掌握类型安全与优雅设计
java·程序员
笑衬人心。1 小时前
在 Mac 上安装 Java 和 IntelliJ IDEA(完整笔记)
java·macos·intellij-idea
SimonKing1 小时前
颠覆传统IO:零拷贝技术如何重塑Java高性能编程?
java·后端·程序员