HttpClient的POST发送请求(参数为JSON)

淩亂°似流年 2022-03-10 04:46 1081阅读 0赞
  1. public String httpSendMsg(String content , String receiveTelsStr) throws IOException {
  2. String url = SmsGlobal.SEND_MSG_URL;
  3. CloseableHttpClient client = HttpClients.createDefault();
  4. HttpPost httpPost = new HttpPost(url);
  5. httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
  6. SendMsgParamsVo sendMsgParamsVo = new SendMsgParamsVo();
  7. sendMsgParamsVo.setFromName(SmsGlobal.SYSTEM_NAME);//设置系统名称
  8. sendMsgParamsVo.setOrgSecret(SmsGlobal.ORGSECRET);//3为内部手机用户
  9. sendMsgParamsVo.setPlatform(SmsGlobal.PLATFORM);//sms为发送短信方式
  10. sendMsgParamsVo.setContent(content);//设置短信内容
  11. sendMsgParamsVo.setUserid_list(receiveTelsStr);//设置接收短信的手机号 不同手机号之间用英文逗号隔开
  12. //jackson把bean变成json
  13. String sendMsgParamsVoStr = objectMapper.writeValueAsString(sendMsgParamsVo);
  14. StringEntity stringEntity = new StringEntity(sendMsgParamsVoStr,"UTF-8");
  15. httpPost.setEntity(stringEntity);
  16. CloseableHttpResponse response = client.execute(httpPost);
  17. HttpEntity entity = response.getEntity();
  18. String result = EntityUtils.toString(entity);
  19. return result;
  20. }

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

发表评论

表情:
评论列表 (有 0 条评论,1081人围观)

还没有评论,来说两句吧...

相关阅读