Springboot HttpClient createDefault @RequestBody 发送请求解决乱码问题

本文介绍了在Springboot中使用HttpClient发送带@RequestBody的POST请求时如何处理乱码问题。通过实例展示了如何将JSON字符串转换为请求参数,并利用RestTemplate进行POST请求,同时确保请求头设置正确的字符集。

ApplyInfoDTO applyInfo=JSON.parseObject(strAppInfo,ApplyInfoDTO.class);
    CancelReqData reqdata= HtInsured.installCancelReqData(applyInfo,date,channelCode);
    String insureJson=JSON.toJSONString(reqdata);

public static String httpSendPost(String url, String strAppInfo) {

  HttpClient hc=null;
  BufferedReader in = null;  
  try {
  hc=HttpClients.createDefault();  
  HttpPost post=new HttpPost(url); 
  StringEntity entity1 = new StringEntity(strAppInfo,"UTF-8");
          entity1.setContentType("application/json");
  post.setEntity(entity1); 
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(20000).setSocketTimeout(30000).build(); 
  post.setConfig(requestConfig); 
  HttpResponse response=hc.execute(post);
  String str="";
  int code = response.getStatusLine().getStatusCode();  
  LogHelper.commoninfo("==========code==========="+code);
      if(code == 200){
         in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));  
         StringBuffer sb = new StringBuffer("");    
         String line = "";    
         String separator = System.getProperty("line.separator");    
      while((line = in.readLine()) != null) {    
             str+=sb.append(line + separator);    
          }     
     }
    if(in!=null) {
    in.close(); 
     }
    
    return str;
} catch (Exception e) {
LogHelper.commonerror("HtInsuredServiceImpl.httpSendPost:" + e.getMessage(), e);
return null;
}

}

@RestController
@RequestMapping(path = "/v1/ht", produces = {"application/json;charset=UTF-8"})

@PostMapping("/htInsuredSubmit")
public ResultDTO<Map<String, String>> htInsuredSubmit(@RequestBody String strAppInfo, HttpServletRequest request){
ResultDTO<Map<String, String>> result=null;
try {
LogHelper.commoninfo(strAppInfo);
result= (ResultDTO<Map<String, String>>) this.restTemplateService.restTemplatePost1(strAppInfo,htInsuredSubmitUrl,
new ResultDTO<>(ResultDTO.CODE_SUCCESS,strAppInfo));
return result;
} catch (Exception e) {
LogHelper.commonerror("HrInsuredController.htInsuredSubmit:" + e.getMessage(), e);
return result;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值