Java HTTP DELETE with Request Body

前端 未结 4 1788
难免孤独
难免孤独 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: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 queryParams,// Query map forms URI
            Map 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?

提交回复
热议问题