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);