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.
I tried HttpURLConnection for similar GET, POST and PUT. But I am not sure how to use the DELETE with a request body.
I have checked in StackOverflow and see this cannot be done, but they are very old answers.
Can someone please help? I'm using spring framework.
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;
}
}