httpClient-HttpPost

一、创建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;
            }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值