JayJona
JayJona

Reputation: 502

how to send http get requests in java and take a specific field

in java what is the easiest way to send http get requests, for example to this link https://jsonplaceholder.typicode.com/todos/1, and take only the id field?

at the moment this is the code i am using but obviously it prints all the content in json format

int responseCode = 0;
try {
    responseCode = httpClient.getResponseCode();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

StringBuilder response = new StringBuilder();
try (BufferedReader in = new BufferedReader(
    new InputStreamReader(httpClient.getInputStream()))) {
    String line;

    while ((line = in.readLine()) != null) {
        response.append(line);
    }


} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Upvotes: 0

Views: 1274

Answers (1)

akourt
akourt

Reputation: 5563

Suppose that you're not limited regarding 3rd party library usage, the following is a very easy example of what you want to achieve.

To do so, it uses both Apache's HTTPClient to perform the GET request and Jackson to deserialize the response.

First you start with creating a model class that representes your expected response object:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Response {

    private Integer id;
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }

}

Note that the class is annotated with @JsonIgnoreProperties(ignoreUnknown = true) which instructs Jackson to ignore any properties that cannot be mapped to the model class (i.e in our case everything other than the id field).

With this in place performing a GET request and retrieving the response's id field can be done as easy as the following example:

public class HttpClientExample {

    public static void main(String... args) {

        try (var client = HttpClients.createDefault()) {
            var getRequest = new HttpGet("https://jsonplaceholder.typicode.com/todos/1");
            getRequest.addHeader("accept", "application/json");

        HttpResponse response = client.execute(getRequest);
        if (isNot2xx(response.getStatusLine().getStatusCode())) {
            throw new IllegalArgumentException("Failed to get with code: " + response.getStatusLine().getStatusCode());
        }

        Response resp = new ObjectMapper().readValue(EntityUtils.toString(response.getEntity()), Response.class);
        System.out.println(resp.getId());

    } catch (IOException e) {
            e.printStackTrace();
    }

    }

    private static boolean isNot2xx(int statusCode) {
        return statusCode != 200;
    }

}

As mentioned above, this example assumes that you can use 3rd party libraries. Also note that if you use Java 11 you can omit using the HTTP client from Apache as the new JDK comes bundled with Java's own HTTP client which offers all the functionality you need to perform your job.

Upvotes: 2

Related Questions