1.构建Post请求
public JSONObject getHttpInfo(Param param) {
HttpPost httpPost;
try {
httpPost = new HttpPost("");
StringEntity stringEntity = new StringEntity(JSON.toJSONString(param), StandardCharsets.UTF_8);
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
} catch (Exception e) {
throw new BusinessException("genPost error" + e.getMessage());
}
return getHttpResponse(httpPost);
}
2.获取请求结果
private JSONObject getHttpResponse(HttpUriRequest request) {
CloseableHttpClient httpClient;
try {
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> true).build();
//创建httpClient
httpClient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy())
.setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
CloseableHttpResponse httpResponse = httpClient.execute(request);
//此处可设置解码方式
BufferedReader reader = IoUtil.getUtf8Reader(httpResponse.getEntity().getContent());
String inputLine;
StringBuilder stringBuffer = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuffer.append(inputLine);
}
reader.close();
JSONObject respResult = JSONObject.parseObject(stringBuffer.toString());
return respResult ;
} catch (Exception e) {
throw new BusinessException("Http请求失败" + e.getMessage());
}
}