Last active
August 19, 2016 20:06
-
-
Save mosampaio/764aaad028c0eb0081d225a051c80bc9 to your computer and use it in GitHub Desktop.
How to consume a json Rest API with Java using Apache Httpclient
This file contains hidden or 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
import org.apache.http.HttpResponse; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClientBuilder; | |
import org.json.JSONArray; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
public class ApacheLibrary { | |
public static void main(String[] args) { | |
CloseableHttpClient httpClient = HttpClientBuilder.create().build(); | |
String url = "https://api.github.com/repos/twilio/twilio-java/contributors"; | |
HttpGet getRequest = new HttpGet(url); | |
getRequest.addHeader("accept", "application/json"); | |
try { | |
HttpResponse response = httpClient.execute(getRequest); | |
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); | |
String jsonContent = br.lines().reduce((s, s2) -> s + s2).get(); | |
JSONArray jsonObj = new JSONArray(jsonContent); | |
System.out.println(jsonObj); | |
} catch (IOException ex) { | |
throw new RuntimeException(ex); | |
} finally { | |
getRequest.releaseConnection(); | |
} | |
} | |
} |
This file contains hidden or 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
apply plugin: 'java' | |
repositories { | |
jcenter() | |
} | |
dependencies { | |
compile 'org.apache.httpcomponents:httpclient:4.5.2' | |
compile 'org.json:json:20160810' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment