带有请求正文的Java HTTP DELETE [英] Java HTTP DELETE with Request Body
问题描述
我有一个外部API,该主体将DELETE与body(JSON)一起使用.我利用Postman REST Client并通过请求正文完成删除,并且工作正常.我正在尝试使用一种方法来自动化此功能.
I have an external API which uses DELETE with the body(JSON). I make use of Postman REST Client and get the delete done with request body and it works fine. I am trying to automate this functionality using a method.
我尝试使用HttpURLConnection进行类似的GET,POST和PUT.但是我不确定如何在请求正文中使用DELETE.
I tried HttpURLConnection for similar GET, POST and PUT. But I am not sure how to use the DELETE with a request body.
我已经检查了StackOverflow,发现无法完成此操作,但是答案很旧.
I have checked in StackOverflow and see this cannot be done, but they are very old answers.
有人可以帮忙吗?我正在使用spring框架.
Can someone please help? I'm using spring framework.
推荐答案
我使用org.apache.http完成了此任务.
I used org.apache.http to get this done.
@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;
}
}
这篇关于带有请求正文的Java HTTP DELETE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!