我是靠谱客的博主 霸气悟空,这篇文章主要介绍HttpClient的POST发送请求(参数为JSON),现在分享给大家,希望可以做个参考。

    public String httpSendMsg(String content , String receiveTelsStr) throws IOException {

        String url = SmsGlobal.SEND_MSG_URL;
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

        SendMsgParamsVo sendMsgParamsVo = new SendMsgParamsVo();
        sendMsgParamsVo.setFromName(SmsGlobal.SYSTEM_NAME);//设置系统名称
        sendMsgParamsVo.setOrgSecret(SmsGlobal.ORGSECRET);//3为内部手机用户
        sendMsgParamsVo.setPlatform(SmsGlobal.PLATFORM);//sms为发送短信方式

        sendMsgParamsVo.setContent(content);//设置短信内容
        sendMsgParamsVo.setUserid_list(receiveTelsStr);//设置接收短信的手机号  不同手机号之间用英文逗号隔开
        //jackson把bean变成json
        String sendMsgParamsVoStr = objectMapper.writeValueAsString(sendMsgParamsVo);
        StringEntity stringEntity = new StringEntity(sendMsgParamsVoStr,"UTF-8");
        httpPost.setEntity(stringEntity);

        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();

        String result = EntityUtils.toString(entity);
        return result;
    }

这里使用的是StringEntity构建的HttpEntity,放到请求体中。注意使用编码,防止乱码。

最后

以上就是霸气悟空最近收集整理的关于HttpClient的POST发送请求(参数为JSON)的全部内容,更多相关HttpClient内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(97)

评论列表共有 0 条评论

立即
投稿
返回
顶部