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

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

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

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

代码如下:

public static String doPost(String url, JSONObject params) {
        String result = "";
        CloseableHttpResponse response = null;
        try {
            //设置请求地址,创建 URIBuilder
            URIBuilder uriBuilder = new URIBuilder(url);
            if (!params.isEmpty()) {
                List<NameValuePair> nvp = new ArrayList<>();
                for (String key : params.keySet()) {
                    nvp.add(new BasicNameValuePair(key, params.getString(key)));
                }
                uriBuilder.setParameters(nvp);
            }
            HttpPost httpPost = new HttpPost(uriBuilder.build());
            httpPost.setConfig(REQUEST_CONFIG);
            //返回json数据时不需要下面一行header
            httpPost.setHeader("Accept", "text/xml");
            //定义Content-Type
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            //发起请求
            response = HTTP_CLIENT.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == CODE) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "utf-8");
            } else {
                log.error("\n请求接口错误,请检查接口是否可以正常访问!");
            }
            log.info("\n发起接口请求信息\n地址:{}\n参数:{}\n请求方式:{}\n请求结果:{}", url, params.toJSONString(), httpPost.getMethod(), result);
        } catch (URISyntaxException | IOException e) {
            log.error("\n请求接口错误,请检查接口是否可以正常访问!\n地址:{},\n参数:{}", url, params.toJSONString());
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                    log.info("关闭连接请求!");
                }
            } catch (IOException e) {
                log.error("关闭发送请求失败!{}", e.getMessage());
            }
        }
        return result;
    }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值