Skip to content

Instantly share code, notes, and snippets.

@iKunalChhabra
Created June 9, 2023 14:51
Show Gist options
  • Save iKunalChhabra/93b092bbc365a3817d0cec175e89a3f1 to your computer and use it in GitHub Desktop.
Save iKunalChhabra/93b092bbc365a3817d0cec175e89a3f1 to your computer and use it in GitHub Desktop.
Get request in Java using Apache HTTP Client
package org.example;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
public class Main {
public static void main(String[] args) {
JSONArray posts = getPosts();
System.out.println(posts.getJSONObject(0).get("title").toString().substring(0, 10));
}
private static JSONArray getPosts() {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String url = "https://jsonplaceholder.typicode.com/posts";
HttpGet request = new HttpGet(url);
request.addHeader("accept", "application/json");
request.addHeader("content-type", "application/json");
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
return new JSONArray(EntityUtils.toString(entity));
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new JSONArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment