Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HTTP DELETE with Request Body

Tags:

java

http

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.

like image 972
DXBKing Avatar asked Apr 05 '17 20:04

DXBKing


People also ask

Can HTTP delete have request body?

Yes it is allowed to include a body on DELETE requests, but it's semantically meaningless.

How do you delete a HTTP request?

there is a simple way for delete and put request, you can simply do it by adding a " _method " parameter to your post request and write " PUT " or " DELETE " for its value!

Can HTTP delete have query parameters?

There's nothing wrong with using DELETE on a collection and filtering by query parameters. Neither the REST dissertation nor the HTTP spec say anything about not doing this. This is different than the answer to the question that @Thilo linked to because the circumstances are different.

What should delete request return?

4.1. A successful response of DELETE requests SHOULD be an HTTP response code 200 (OK) if the response includes an entity describing the status. The status should be 202 (Accepted) if the action has been queued.


1 Answers

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;
    }
}
like image 105
DXBKing Avatar answered Nov 14 '22 23:11

DXBKing