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.dangjian.common.utils.http;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
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(); }
}
使用时:
/**
* Http协议Delete请求 手环(第三方接口)
*
* @param url 请求url
* @param json 参数对象json字符串
* @param imei 手环串号(这儿业务需要设置到请求头)
* @param cpid 手环授权cpid(这儿业务需要设置到请求头)
* @param key 手环授权key(这儿业务需要设置到请求头)
* @return 数据
* @throws Exception 异常信息
*/
public static String httpDeleteForDeviceBracelets(String url, String json, String imei, String cpid, String key) throws Exception {
//初始HttpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建Put对象
// HttpDelete httpDelete = new HttpDelete(url);
HttpDeleteWithBody httpDeleteWithBody = new HttpDeleteWithBody(url);
//设置Content-Type
httpDeleteWithBody.setHeader("Content-Type", "application/json");
//设置其他Header
httpDeleteWithBody.setHeader("cpid", cpid);
httpDeleteWithBody.setHeader("key", key);
httpDeleteWithBody.setHeader("imei", imei);
//写入JSON数据参数
httpDeleteWithBody.setEntity(new StringEntity(json));
//发起请求,获取response对象
CloseableHttpResponse response = httpClient.execute(httpDeleteWithBody);
//获取请求码
//response.getStatusLine().getStatusCode();
//获取返回数据实体对象
HttpEntity entity = response.getEntity();
//转为字符串
return EntityUtils.toString(entity, "UTF-8");
}
测试后成功!
参考自 : https://blog.csdn.net/xinghen1993/article/details/103999978?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2allsobaiduend~default-2-103999978.nonecase&utm_term=httpdelete%E4%BC%A0%E5%8F%82&spm=1000.2123.3001.4430