9

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.

DXBKing
  • 275
  • 1
  • 3
  • 10
  • 1
    Does this help you? http://stackoverflow.com/questions/299628/is-an-entity-body-allowed-for-an-http-delete-request. It seems that with DELETE, the request body should be ignored. – jrook Apr 05 '17 at 20:58
  • I have read that article, however, the external API which I use has to have the body – DXBKing Apr 05 '17 at 21:01
  • Which third-party API is this? Is it a third-party API used by a third-party product, or a third-party API used by a product you are developing? In the former case, you're pretty much stuck with it, but in the latter case, your organization could choose to use a library with a more common (better supported) syntax. – shoover Apr 05 '17 at 21:44
  • It's an in-house application service of my org, accessible only through the same network. I'm trying to hit that production API with my API. – DXBKing Apr 05 '17 at 23:01
  • Typically only POST, PUT and PATCH use request bodies, so at least that is not a REST API - seems to be a bad design at all. – Arne Burmeister Apr 06 '17 at 21:25

4 Answers4

13

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;
    }
}
DXBKing
  • 275
  • 1
  • 3
  • 10
  • 1
    Got the answer from https://daweini.wordpress.com/2013/12/20/apache-httpclient-send-entity-body-in-a-http-delete-request/ – DXBKing Apr 06 '17 at 23:08
5

If you are using Spring, you can use RestTemplate to generate the client request. In this case you could use RestTemplate.exchange and provide the url, http method and request body. Something like (not tested, but you get the idea):

RestTemplate restTemplate = new RestTemplate();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
restTemplate.exchange(url, HttpMethod.DELETE, request, null);
Jeff Smith
  • 695
  • 6
  • 14
2

This code worked for me:-

  • You set content type by httpCon.setRequestProperty
  • You set the request Method by httpCon.setRequestMethod
  • Write the json body into OutputStreamWriter, in my sample, i converted Java object to json using Jackson ObjectMapper

    URL url = new URL("http://localhost:8080/greeting");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestProperty(
                    "Content-Type", "application/json");
    httpCon.setRequestMethod("DELETE");
    OutputStreamWriter out = new OutputStreamWriter(
                    httpCon.getOutputStream());
    ObjectMapper objectMapper = new ObjectMapper();
    out.write(objectMapper.writeValueAsString(new Greeting("foo")));
    out.close();
    httpCon.connect();
    
mgalala
  • 106
  • 8
-1

Isn't easy just to override the getMethod() method of the HttpPost class?

private String curl(                    // Return JSON String
        String method,                  // HTTP method, for this example the method parameter should be "DELETE", but it could be PUT, POST, or GET.
        String url,                     // Target URL  
        String path,                    // API Path
        Map<String, Object> queryParams,// Query map forms URI
        Map<String, Object> postParams) // Post Map serialized to JSON and is put in the header
        throws Error,               // when API returns an error
        ConnectionClosedException       // when we cannot contact the API
{
   HttpClient client = HttpClients.custom()
            .setDefaultRequestConfig(
                    RequestConfig.custom()
                            .setCookieSpec(CookieSpecs.STANDARD)
                            .build()
            ).build();


    HttpPost req = new HttpPost(){
        @Override
        public String getMethod() {
            // lets override the getMethod since it is the only
            // thing that differs between each of the subclasses
            // of HttpEntityEnclosingRequestBase. Let's just return
            // our method parameter in the curl method signature.
            return method;
        }
    };

    // set headers
    req.setHeader("user-agent", "Apache");
    req.setHeader("Content-type", "application/json");
    req.setHeader("Accept", "application/json");

    try {
        // prepare base url
        URIBuilder uriBuilder = new URIBuilder(url + path);

        if (method.equals("GET")){
            queryParams.forEach((k, v)-> uriBuilder.addParameter(k, v.toString()));
        }else{
            String postPramsJson = new Gson().toJson(postParams);
            req.setEntity(new StringEntity(postPramsJson));
        }

        // set the uri
        req.setURI(uriBuilder.build().normalize());

        // execute the query
        final HttpResponse response = client.execute(req);

        //
        if (response.getEntity() != null) {
            if(response.getStatusLine().getStatusCode() == 200){
                 return EntityUtils.toString(response.getEntity());
            }
            logger.error("ERROR: Response code " + response.getStatusLine().getStatusCode() +
                     ", respnse: " + EntityUtils.toString(responseEntry));
        }
        throw new Error("HTTP Error");
    } catch (Exception e) {
        logger.error("Connection error", e);
        throw new ConnectionClosedException("Cannot connect to " + url);
    }
}

The point is rather than having to add another class to your package... Why not just override getMethod() in an already sub-classed object of HttpEntityEnclosingRequestBase?

Ajay Mistry
  • 951
  • 1
  • 14
  • 30
Siraj
  • 329
  • 2
  • 7