Created
June 9, 2023 14:51
-
-
Save iKunalChhabra/93b092bbc365a3817d0cec175e89a3f1 to your computer and use it in GitHub Desktop.
Get request in Java using Apache HTTP Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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