Java HTTP DELETE with Request Body

前端 未结 4 1789
难免孤独
难免孤独 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:11

    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();
      
    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
  • 2021-01-20 01:22

    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?

    0 讨论(0)
  • 2021-01-20 01:25

    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);
    
    0 讨论(0)
提交回复
热议问题