Java HTTP DELETE with Request Body

前端 未结 4 1813
难免孤独
难免孤独 2021-01-20 00:44

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 a

4条回答
  •  灰色年华
    2021-01-20 01:21

    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;
        }
    }
    

提交回复
热议问题