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