Httpclient 发送 post 请求封装json 格式参数

﹏ヽ暗。殇╰゛Y 2022-12-13 14:05 517阅读 0赞

Httpclient 发送 post 请求可以封装多格式的参数,这篇我们封装json格式的:

1、客户端代码如下:

  1. /**
  2. * 参数以json形式传送
  3. * @param request
  4. * @return
  5. * @throws IOException
  6. */
  7. public NmpResponse doPostJson(NmpRequest request) throws IOException {
  8. logger.info("------------开始POST请求-nmpHttpClient-----------");
  9. HttpClient httpClient = new HttpClient();
  10. httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
  11. PostMethod postMethod = new PostMethod(NMP_ROOT_URL+request.getUrl());
  12. postMethod = setHeaderAuthInfo(postMethod);
  13. //添加请求参数
  14. String jsonParams = request.getJsonParam();
  15. System.out.println("推送参数:"+jsonParams);
  16. postMethod.setRequestEntity(new StringRequestEntity(jsonParams,null,null));
  17. NmpResponse response = new NmpResponse();
  18. try {
  19. logger.info("------------开始执行POST请求,url:{}------------",NMP_ROOT_URL+request.getUrl());
  20. int statusCode = httpClient.executeMethod(postMethod);
  21. logger.info("------------POST请求结束,code={}------------",statusCode);
  22. if (statusCode == 200){
  23. response.setRespBody(postMethod.getResponseBody());
  24. response.setResponseStr(postMethod.getResponseBodyAsString());
  25. response.setRespHeaders(postMethod.getRequestHeaders());
  26. } else{
  27. logger.error("请求出错code={}:{}" ,statusCode ,postMethod.getStatusLine());
  28. }
  29. } catch (IOException e){
  30. logger.error("请求出错IOException:{}" ,e);
  31. throw e;
  32. } finally {
  33. postMethod.releaseConnection();
  34. logger.info("------------结束POST请求-nmpHttpClient-----------");
  35. }
  36. return response;
  37. }

2、服务端接收代码:

  1. @RequestMapping(value = "/download/getListData")
  2. public Object queryPartitionList(@RequestBody PartitionVO partitionVO){
  3. if(Objects.isNull(partitionVO) ||StringUtils.isEmpty(partitionVO.getLayName()) ||CollectionUtils.isEmpty(partitionVO.getParNameList())){
  4. logger.error("Method:queryPartitionList 入参不能为空");
  5. return new JSONObject();
  6. }
  7. if (StringUtils.isEmpty(partitionVO.getProductVersion())){
  8. partitionVO.setProductVersion(Constant.ProductVersionLastest);
  9. }
  10. JSONObject jsonObject = new JSONObject();
  11. //业务代码省略
  12. return jsonObject;
  13. }

3、服务端 partitionVO和客户端 jsonParams 数据里的参数一一对应。

发表评论

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

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

相关阅读