当前位置:   article > 正文

Java中怎么使用httpclick发送application/x-www-form-urlencoded请求并接收text/xml数据呢?

Java中怎么使用httpclick发送application/x-www-form-urlencoded请求并接收text/xml数据呢?

项目中遇到一个请求方式要求:

1 、POST 请求
2 、Content-Type: text/xml; charset=utf-8

项目是Java代码 使用的httpclick发送的请求,接下来让我看下如何实现,本部分只提供核心请求代码,之前分享过httpclick发送请求工具类,有兴趣的小伙伴可以查看下之前文章(●'◡'●)

代码如下:

  1. public static String doPost(String url, JSONObject params) {
  2. String result = "";
  3. CloseableHttpResponse response = null;
  4. try {
  5. //设置请求地址,创建 URIBuilder
  6. URIBuilder uriBuilder = new URIBuilder(url);
  7. if (!params.isEmpty()) {
  8. List<NameValuePair> nvp = new ArrayList<>();
  9. for (String key : params.keySet()) {
  10. nvp.add(new BasicNameValuePair(key, params.getString(key)));
  11. }
  12. uriBuilder.setParameters(nvp);
  13. }
  14. HttpPost httpPost = new HttpPost(uriBuilder.build());
  15. httpPost.setConfig(REQUEST_CONFIG);
  16. //返回json数据时不需要下面一行header
  17. httpPost.setHeader("Accept", "text/xml");
  18. //定义Content-Type
  19. httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
  20. //发起请求
  21. response = HTTP_CLIENT.execute(httpPost);
  22. if (response.getStatusLine().getStatusCode() == CODE) {
  23. HttpEntity entity = response.getEntity();
  24. result = EntityUtils.toString(entity, "utf-8");
  25. } else {
  26. log.error("\n请求接口错误,请检查接口是否可以正常访问!");
  27. }
  28. log.info("\n发起接口请求信息\n地址:{}\n参数:{}\n请求方式:{}\n请求结果:{}", url, params.toJSONString(), httpPost.getMethod(), result);
  29. } catch (URISyntaxException | IOException e) {
  30. log.error("\n请求接口错误,请检查接口是否可以正常访问!\n地址:{},\n参数:{}", url, params.toJSONString());
  31. throw new RuntimeException(e.getMessage());
  32. } finally {
  33. try {
  34. if (response != null) {
  35. response.close();
  36. log.info("关闭连接请求!");
  37. }
  38. } catch (IOException e) {
  39. log.error("关闭发送请求失败!{}", e.getMessage());
  40. }
  41. }
  42. return result;
  43. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/782849
推荐阅读
相关标签
  

闽ICP备14008679号