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。

//重写
package com.pizza.util;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;


public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
    public static final String METHOD_NAME = "DELETE";
    public String getMethod() { return METHOD_NAME; }

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

使用时:

public static HttpResponse Delete(String url,
                                String cookie,
                                Header[] headers,
                                String jsonString) throws IOException {
    HttpResponse response;
    CloseableHttpClient client = HttpClientBuilder.create().build();

    HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
    delete.setEntity(new StringEntity(jsonString));

    delete.setHeaders(headers);
    delete.addHeader("content-type", "application/json");
    delete.addHeader("Cookie", cookie);

    response = client.execute(delete);
    return response;
}

 

发布了33 篇原创文章 · 获赞 16 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览