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