HttpPost、HttpPut继承了HttpEntityEnclosingRequestbase类,所以有setEntity方法。
一般的 DELETE 请求参数是置于路径中的,所以一般的 httpDelete 不会像 httpPost 一样使用如下方式传递 JSON参数
HttpPost httpPost = new HttpPost(actionUrl); StringEntity entity = new StringEntity(jsonBody, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); response = httpClient.execute(httpPost);解决方式
为了使用和 post put 类似的方式,这里我们自己定义一个 httpDelete 但也继承 HttpEntityEnclosingRequestbase 从而获得 setEntity 的方法;
类如下定义,几乎是 直接复制 httppost 的继承方式;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.methods.HttpEntityEnclosingRequestbase;
import java.net.URI;
@NotThreadSafe
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestbase {
public static final String METHOD_NAME = "DELETE";
@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);
}
public HttpDeleteWithBody() {
super();
}
}
然后在原有代码替换 httppost 即可 一般的post使用方法见最上面问题的示例代码
我们定义后的 httpdelete 替换如下:
// 上面自定义的类 HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(actionUrl); StringEntity entity = new StringEntity(jsonBody, ContentType.APPLICATION_JSON); httpDelete.setEntity(entity); response = httpClient.execute(httpDelete);
直接替换后即可使用
HttpEntityEnclosingRequestbase 所在 Maven 依赖org.apache.httpcomponents httpcore 4.4.1



