一、创建httpClient
方法一:
private static final CloseableHttpClient httpClient = HttpClients.createDefault();
方法二:
private static final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
方法一的底层也就是方法二:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210617152700221.png)
二、构建post请求json
// 字符串编码
StringEntity entity = new StringEntity(JSON.toJSONString(userNotificationReq), Consts.UTF_8);
// 设置content-type
entity.setContentType("application/json");
HttpPost httpPost = new HttpPost(notificationUrl);
// 接收参数设置
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(entity);
三、执行
response = httpClient.execute(httpPost);
四、获取返回值
if(response.getStatusLine().getStatusCode() == HttpStatus.HTTP_OK){
// 得到entity
HttpEntity responseEntity = response.getEntity();
// 得到字符串
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, charset);
}
BaseResult<Long> baseResult = JSONObject.parseObject(result, new TypeReference<BaseResult<Long>>() {});
if(!baseResult.isSuccess()){
log.error("调用消息推送异常:"+baseResult.getMsg());
throw OceanException.NOTIFICATION_SEND_ERROR;
}
log.info("send notification success,返回:{}",baseResult.getData());
return baseResult.getData();
} else {
log.error("send notification error,请求返回错误,code:{},ReasonPhrase:{}",response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase());
throw OceanException.NOTIFICATION_SEND_ERROR;
}