我有一個外部API,它使用DELETE和正文(JSON)。我利用郵遞員REST客戶端並使用請求正文完成刪除,並且工作正常。我正在嘗試使用一種方法來自動化此功能。帶請求正文的Java HTTP DELETE
我試過類似的GET,POST和PUT的HttpURLConnection。但我不確定如何在請求主體中使用DELETE。
我檢查了StackOverflow,看到這不能完成,但他們是非常古老的答案。
有人可以幫忙嗎?我正在使用spring框架。
我有一個外部API,它使用DELETE和正文(JSON)。我利用郵遞員REST客戶端並使用請求正文完成刪除,並且工作正常。我正在嘗試使用一種方法來自動化此功能。帶請求正文的Java HTTP DELETE
我試過類似的GET,POST和PUT的HttpURLConnection。但我不確定如何在請求主體中使用DELETE。
我檢查了StackOverflow,看到這不能完成,但他們是非常古老的答案。
有人可以幫忙嗎?我正在使用spring框架。
我用org.apache.http來完成這件事。
@NotThreadSafe
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
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 String[] sendDelete(String URL, String PARAMS, String header) throws IOException {
String[] restResponse = new String[2];
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(URL);
StringEntity input = new StringEntity(PARAMS, ContentType.APPLICATION_JSON);
httpDelete.addHeader("header", header);
httpDelete.setEntity(input);
Header requestHeaders[] = httpDelete.getAllHeaders();
CloseableHttpResponse response = httpclient.execute(httpDelete);
restResponse[0] = Integer.toString((response.getStatusLine().getStatusCode()));
restResponse[1] = EntityUtils.toString(response.getEntity());
return restResponse;
}
}
得到了答案從 https://daweini.wordpress.com/2013/12/20/apache-httpclient-send-entity-body-in-a-http-delete-請求/ – DXBKing
如果您使用的是Spring,則可以使用RestTemplate
來生成客戶端請求。在這種情況下,您可以使用RestTemplate.exchange並提供url,http方法和請求正文。喜歡的東西(未測試,但你的想法):
RestTemplate restTemplate = new RestTemplate();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
restTemplate.exchange(url, HttpMethod.DELETE, request, null);
這會丟下身體,總是返回400 –
此代碼爲我工作: -
寫JSON身體成OutputStreamWriter,我的樣品中,我使用傑克遜ObjectMapper
轉換Java對象JSON
這對你有幫助嗎? http://stackoverflow.com/questions/299628/is-an-entity-body-allowed-for-an-http-delete-request。看來用DELETE,請求體應該被忽略。 – jrook
我已閱讀過那篇文章,但是,我使用的外部API必須具有正文 – DXBKing
這是哪個第三方API?它是由第三方產品使用的第三方API,還是由您正在開發的產品使用的第三方API?在前一種情況下,您幾乎堅持使用它,但在後一種情況下,您的組織可以選擇使用具有更常見(更好支持)語法的庫。 – shoover