Search code examples
javahttpclient

How can I change HttpGet into HttpPost?


I am new to java and I am learning slowly but surely; any insight to this would be greatly appreciated.

I have some functional HttpGet code that I want to adapt into HttpPost so that I can open and send the contents of a local JSON file. I've attempted numerous methods but they've all failed and I have now confused myself.

This is the HttpPost code I have converted so far. It has only the change of HttpGet to HttpPost. import org.apache.http.client.methods.HttpPost; is present. What should I be doing?

@Component
public class ServiceConnector {
    private final HttpClient client;

    public ServiceConnector() {
        client = HttpClientBuilder.create().build();
    }

    public String post(String url, String acceptHeader, Optional<String> bearerToken) throws UnauthorizedException {
        HttpPost request = new HttpPost(url);
        request.addHeader("Accept", acceptHeader);
        if (bearerToken.isPresent()) {
            request.addHeader("Authorization", "Bearer " + bearerToken.get());
        }

        try {
            HttpResponse response = client.execute(request);

            if (response.getStatusLine().getStatusCode() == 401) {
                throw new UnauthorizedException();
            }
            return EntityUtils.toString(response.getEntity());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Edited with "post" where "get" existed.


Solution

  • You can try something like this, where you prepare the post request with the JSON and then execute it:

    @Component
    public class ServiceConnector {
        private final HttpClient client;
    
    
        public ServiceConnector() {
            client = HttpClientBuilder.create().build();
        }
        public String post(String url, String acceptHeader, Optional<String> bearerToken) throws UnauthorizedException {
    
        try {
            HttpPost request = new HttpPost(url);
            request.addHeader("Accept", acceptHeader);
            if (bearerToken.isPresent()) {
                request.addHeader("Authorization", "Bearer " + bearerToken.get());
            }
            StringEntity params =new StringEntity("details {\"name\":\"myname\",\"age\":\"20\"} ");
        // You could open, read, and convert the file content into a json-string (use GSON lib here)
            request.addHeader("content-type", "application/json");
            request.addHeader("Accept","application/json");
            request.setEntity(params);
            HttpResponse response = client.execute(request);
    
            // handle response here...
        }catch (Exception ex) {
            // handle exception here
        } finally {
            client.getConnectionManager().shutdown();
        }
    }