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

深碍√TFBOYSˉ_ 2022-12-13 14:04 625阅读 0赞

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

1、客户端代码如下:

  1. public NmpResponse doPostMap(NmpRequest request) throws IOException {
  2. logger.info("------------开始POST请求-nmpHttpClient-----------");
  3. HttpClient httpClient = new HttpClient();
  4. httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
  5. PostMethod postMethod = new PostMethod(NMP_ROOT_URL+request.getUrl());
  6. postMethod = setHeaderAuthInfo(postMethod);
  7. //添加请求参数
  8. Map<String,String> params = request.getParams();
  9. if(null != params && params.size()>0){
  10. for(Map.Entry<String,String> param : params.entrySet()) {
  11. String key = param.getKey();
  12. String paramValue = params.get(key);
  13. postMethod.addParameter(key, paramValue);
  14. }
  15. }
  16. NmpResponse response = new NmpResponse();//自己封装的一个返回对象
  17. try {
  18. logger.info("------------开始执行POST请求,url:{}------------",NMP_ROOT_URL+request.getUrl());
  19. int statusCode = httpClient.executeMethod(postMethod);
  20. logger.info("------------POST请求结束,code={}------------",statusCode);
  21. if (statusCode == 200){
  22. response.setRespBody(postMethod.getResponseBody());
  23. response.setResponseStr(postMethod.getResponseBodyAsString());
  24. response.setRespHeaders(postMethod.getRequestHeaders());
  25. } else{
  26. logger.error("请求出错code={}:{}" ,statusCode ,postMethod.getStatusLine());
  27. }
  28. } catch (IOException e){
  29. logger.error("请求出错IOException:{}" ,e);
  30. throw e;
  31. } finally {
  32. postMethod.releaseConnection();
  33. logger.info("------------结束POST请求-nmpHttpClient-----------");
  34. }
  35. return response;
  36. }

2、服务端就可以用map 格式的数据接收参数了。

发表评论

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

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

相关阅读