Simple HTTP GET Request2
Commons Http Client is a HTTP agent implementation in java supporting
client-side authentication, HTTP state management and HTTP connection management.
This requires the libraries httpclient-4.1.2.jar, httpcore-4.1.2.jar,
httpmime-4.1.2.jar, httpclient-cache-4.1.2.jar, commons-codec.jar and
commons-logging-1.1.1.jar to be in classpath.
The following example shows how to make Http Get request through Http Client.
package com.bethecoder.tutorials.commons_httpclient;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class SimpleGetRequestTest2 {
/**
* @param args
*/
public static void main ( String [] args ) {
HttpClient httpclient = new DefaultHttpClient () ;
try {
HttpHost targetHost = new HttpHost ( "finance.google.com" , 80 , "http" ) ;
HttpGet getRequest = new HttpGet ( "/finance/info?client=ig&q=NASDAQ:GOOG" ) ;
System.out.println ( "Requesting : " + targetHost ) ;
HttpResponse rsp = httpclient.execute ( targetHost, getRequest ) ;
HttpEntity entity = rsp.getEntity () ;
System.out.println ( "\n\nResponse : " ) ;
if ( entity != null ) {
System.out.println ( EntityUtils.toString ( entity )) ;
}
} catch ( ClientProtocolException e ) {
e.printStackTrace () ;
} catch ( IOException e ) {
e.printStackTrace () ;
} finally {
httpclient.getConnectionManager () .shutdown () ;
}
}
}
It gives the following output,
Requesting : http://finance.google.com:80
Response :
// [
{
"id": "694653"
,"t" : "GOOG"
,"e" : "NASDAQ"
,"l" : "600.97"
,"l_cur" : "600.97"
,"s": "0"
,"ltt":"3:50PM EST"
,"lt" : "Mar 9, 3:50PM EST"
,"c" : "-6.17"
,"cp" : "-1.02"
,"ccol" : "chr"
}
]