Java Apache asynchronous HttpClient REST (RESTful) client example
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 ca.i88.example; | |
import java.io.*; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.Future; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
import org.apache.http.HttpEntity; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; | |
import org.apache.http.impl.nio.client.HttpAsyncClients; | |
/** | |
* This example demonstrates a way to call a URL using the Apache | |
* CloseableHttpAsyncClient HttpGet and HttpResponse classes. | |
*/ | |
public class ApacheHttpRestClient { | |
public final static void main(String[] args) { | |
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); | |
httpclient.start(); | |
try { | |
// Example URL : this yahoo weather call returns results as an rss (xml) feed | |
HttpGet request = new HttpGet("https://open.canada.ca/data/en/api/3/action/package_search?q=spending"); | |
// Execute HTTP request | |
Future<HttpResponse> future = httpclient.execute(request, null); | |
HttpResponse response = future.get(); | |
System.out.println("----------------------------------------"); | |
System.out.println(response.getStatusLine()); | |
System.out.println("----------------------------------------"); | |
// Get hold of the response entity | |
HttpEntity entity = response.getEntity(); | |
byte[] buffer = new byte[1024]; | |
if (entity != null) { | |
try (InputStream inputStream = entity.getContent() // Closing the input stream will trigger connection release | |
) { | |
int bytesRead = 0; | |
BufferedInputStream bis = new BufferedInputStream(inputStream); | |
while ((bytesRead = bis.read(buffer)) != -1) { | |
String chunk = new String(buffer, 0, bytesRead); | |
System.out.println(chunk); | |
} | |
} catch (IOException ex) { | |
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex); | |
// In case of an unexpected exception you may want to abort | |
// the HTTP request in order to shut down the underlying | |
// connection immediately. | |
request.abort(); | |
} | |
} | |
} catch (InterruptedException | ExecutionException ex) { | |
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
} | |
} |
Comments
Post a Comment