HttpDelete携带json参数(body)的操作示例

1.Httpclient 中常用的请求有2个,HttpPost 和 HttpGet,一般 HttpPost 对传参Json 的处理是:

HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(jsonString));

2.但HttpDelete携带json参数时,不支持setEntity方法,原因是:

在HttpMethods中,包含HttpGet, HttpPost, HttpPut, HttpDelete等类来实现http的常用操作。其中,HttpPost继承自HttpEntityEnclosingRequestBase,HttpEntityEnclosingRequestBase类又实现了HttpEntityEnclosingRequest接口,实现了setEntity的方法。 而HttpDelete继承自HttpRequestBase,没有实现setEntity的方法,因此无法设置HttpEntity对象。

解决方案:重写一个自己的HttpDeleteWithBody类,继承自HttpEntityEnclosingRequestBase,覆盖其中的getMethod方法,从而返回DELETE。

/**
        * date: 2020/6/10 10:43
        *  重写HttpDelete
        * @author xn_liutao
        * @since JDK 1.8
        */
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {

    public static final String METHOD_NAME = "DELETE";

    public HttpDeleteWithBody() {
        super();
    }

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

    public HttpDeleteWithBody(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    public HttpDeleteWithBody(final URI uri) {
        super();
        setURI(uri);
    }

}

3.使用重写的类发送请求:

   /**
     * Delete请求传输JSON参数 例如:{'a':'b'}
     * Content-type:application/json
     *
     * @param url url地址
     * @param
     * @return`1
     */
    public static JSONObject httpDel(String url, Map<String, String> params) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClientConfig.getHttpClient();
        JSONObject jsonResult = null;
        HttpDeleteWithBody httpDel = new HttpDeleteWithBody(url);
        httpDel.setHeader("Content-type", "application/json; charset=utf-8");
        try {
            if (null != params) {
                // 构建消息实体 Map转json字符串
                StringEntity entity = new StringEntity(JSON.toJSONString(params), ContentType.APPLICATION_JSON);
                httpDel.setEntity(entity);
            }
            CloseableHttpResponse response = httpClient.execute(httpDel);
            return convertResponse(response);
        } catch (IOException e) {
            LOGGER.error("delete请求提交失败:" + url, e);
        } finally {
            httpDel.releaseConnection();
        }
        return jsonResult;
    }

参考文章:https://blog.csdn.net/xinghen1993/article/details/103999978

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值