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;
}