今天在使用HttpDelete执行DELETE操作的时候,发现HttpDelete不支持setEntity方法,所以不能携带body信息。 ????????其原因是在HttpMethods中,包含HttpGet, HttpPost, HttpPut, HttpDelete等类来实现http的常用操作。其中,HttpPost继承自HttpEntityEnclosingRequestBase,HttpEntityEnclosingRequestBase类又实现了HttpEntityEnclosingRequest接口,实现了setEntity的方法。 而HttpDelete继承自HttpRequestBase,没有实现setEntity的方法,因此无法设置HttpEntity对象。
1、httpclient get 传json字符串作为参数
????????我们的解决方案是重写一个MyHttpGet类,继承自HttpEntityEnclosingRequestBase,覆盖其中的getMethod方法,从而返回GET。
class HttpGetWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "GET";
HttpGetWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
HttpGetWithBody(final URI uri) {
super();
setURI(uri);
}
HttpGetWithBody() {
super();
}
public String getMethod() {
return METHOD_NAME;
}
}
?2、调用方式
public static String doGet(String url, Map<String, String> headers, List<String> idList) {
CloseableHttpClient httpclient = getHttpClient();
CloseableHttpResponse response = null;
try {
HttpGetWithBody httpGet = new HttpGetWithBody(url);
setHeader(httpGet, headers);
httpGet.setEntity(new StringEntity(idList.toString()));
response = httpclient.execute(httpGet);
return getResult(response);
} catch (Exception e) {
log.error("HttpUtil.doGet error,url:{},Header:{}", url, JSON.toJSONString(headers), e);
} finally {
closeClient(httpclient, response);
}
return null;
}
3、httpclient delete 传json字符串作为参数
????????我们的解决方案是重写一个MyHttpDelete类,继承自HttpEntityEnclosingRequestBase,覆盖其中的getMethod方法,从而返回Delete。
public class HttpDelete extends HttpRequestBase {
public static final String METHOD_NAME = "DELETE";
public HttpDelete() {
}
public HttpDelete(URI uri) {
this.setURI(uri);
}
public HttpDelete(String uri) {
this.setURI(URI.create(uri));
}
public String getMethod() {
return "DELETE";
}
}
4、调用方式
public static String doDelete(String url, Map<String, Object> params, Map<String, String> headers) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = getHttpClient();
StringBuilder urlBuilder = new StringBuilder(url);
int i = 0;
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
urlBuilder.append((i == 0) ? "?" : "&");
urlBuilder.append(entry.getKey()).append("=").append(entry.getValue());
i++;
}
}
HttpDelete httpDelete = new HttpDelete(urlBuilder.toString());
setHeader(httpDelete, headers);
response = httpClient.execute(httpDelete);
return getResult(response);
} catch (Exception e) {
log.error("HttpUtil.doDelete error,url:{},params:{},Header:{}", url, JSON.toJSONString(params), JSON.toJSONString(headers), e);
} finally {
closeClient(httpClient, response);
}
return null;
}
?
?
|