我有一个外部API,它与body(JSON)一起使用DELETE。我利用Postman REST Client并通过请求正文完成删除,并且工作正常。我正在尝试使用一种方法来自动化此功能。
我尝试使用HttpURLConnection进行类似的GET,POST和PUT。但是我不确定如何将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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句