Java与C#请求https默认security protocol的区别

本文探讨了C#中使用HttpClient访问HTTPS接口时遇到的SocketException,并重点介绍了如何通过重置SecurityProtocol来解决,涉及默认SSL协议升级和Java SDK的对比。

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

背景:c#访问https接口出现"SocketException: 远程主机强迫关闭了一个现有的连接",jdk1.8无异常。

C#默认使用SSL3|tsl协议

异常代码:

String url="";
HttpClient client = new HttpClient();
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
Console.WriteLine(System.Net.ServicePointManager.SecurityProtocol);
Task<HttpResponseMessage> html = client.SendAsync(httpRequestMessage);
Console.WriteLine(html.Result.Content.ReadAsStringAsync().Result);

默认SSL协议截图:
在这里插入图片描述
异常截图:
在这里插入图片描述

重置security protocol安全协议后示例代码

String url="";
HttpClient client = new HttpClient();
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
//设置安全协议类型
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Task<HttpResponseMessage> html = client.SendAsync(httpRequestMessage);
Console.WriteLine(html.Result.Content.ReadAsStringAsync().Result);

Jdk1.8默认安全协议:[“TLSv1”, “TLSv1.1”, “TLSv1.2”]

默认安全协议查看代码:

SSLContext context = SSLContext.getInstance("SSL");
context.init(null, null, null);
SSLParameters defaultSSLParameters = context.getDefaultSSLParameters();

DEBUG截图:
在这里插入图片描述
示例代码:

//RestTemplate直接访问也可以,这里主要是模拟HttpClient与C#的区别
HttpRequest get = HttpUtil.createGet("");
Map<String, String> headers = new HashMap<>();
//设置请求头
headers.put("Cookie", "*");
headers.put("Host", "*");
headers.put("Accept-Encoding", "gzip, deflate, br");
headers.put("Accept-Language", "zh-CN,zh;q=0.9");
headers.put("Cache-Control", "max-age=0");
headers.put("Connection", "keep-alive");
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36");
get.addHeaders(headers);
HttpResponse execute = get.execute();
String body = execute.body();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值