HttpClient中DELETE请求,是没有办法带参数的。因为setEntity()方法是抽象类HttpEntityEnclosingRequestBase类里的方法,HttpPost继承了该类,而HttpDelete类继承的是HttpRequestBase类。下面是没有setEntity()方法的。
需要自己创建一个新类,然后照着HttpPost的抄一遍,让新类能够调用setEntity()方法
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
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();
}
}
public static String jsonDeleteRequest(final String url, final Map<String, Object> param) throws Exception {
//解决https请求证书的问题
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> true);
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory())
.register("https", socketFactory).build();
HttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
String responseBody = null;
// 创建默认的httpClient实例.
// final CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//以post方式请求网页
final HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
//将参数转为JSON格式
final Gson gson = new Gson();
final String jsonParam = gson.toJson(param);
delete.setHeader("Content-Type", "application/json;charset=UTF-8");
delete.setHeader("accept","application/json");
//将POST参数以UTF-8编码幷包装成表单实体对象
final StringEntity se = new StringEntity(jsonParam, "UTF-8");
se.setContentType("text/json");
delete.setEntity(se);
final CloseableHttpResponse response = httpClient.execute(delete);
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
logger.info("准备获取返回结果");
responseBody = EntityUtils.toString(entity, "UTF-8");
logger.info("获取返回结果为:" + responseBody);
}
} finally {
response.close();
}
logger.info(responseBody);
}catch(Exception e){
logger.error("接口请求失败:url=" + url, e);
}finally {
// 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源
httpClient.getConnectionManager().shutdown();
}
return responseBody;
}