调用post接口解决Received fatal alert: protocol_version; nested exception is javax.net.ssl.SSLException问题

java调用post接口

报错原因

已知调用方为java1.7,被调用方java1.8,由于协议不匹配导致调用异常,在postman测试下又是正常的,让对端修改显然不是很合理,找了网上各种办法参考下解决(如有侵权请联系),需要匹配相对应的协议。

解决代码示例

import javax.net.ssl.SSLContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.StringEntity;

import net.sf.json.JSONObject;

// 协议设置为TSLv1.2,如果还是有问题需要再改版本尝试
SSLContext ctx = SSLContexts.custom().useProtocol(“TLSv1.2”).build();
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(ctx)).build();
// url 为post接口全名
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
JSONObject jsonParam= new JSONObject();
jsonParam.put(“name”,“zhangsan”);
URLEncoder.encode(jsonParam.toString(),“utf-8”); //url编码
StringEntity stringEntity = new StringEntity(jsonParam.toString(),Charset.forName(“UTF-8”));
stringEntity.setContentType(MediaType.APPLICATION_JSON+“”);
httpPost.setEntity(stringEntity);
httpPost.addHeader(“Content-type”,“application/json; charset=utf-8”);
httpPost.setHeader(“Accept”, “application/json”);
response = httpClient.execute(httpPost);
org.apache.http.HttpEntity entity = (org.apache.http.HttpEntity) response.getEntity();
String responseEntity = EntityUtils.toString((org.apache.http.HttpEntity) entity,StandardCharsets.UTF_8);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值