How to read HTTP Response Status
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 read response status through Commons Http Client.
package com.bethecoder.tutorials.commons_httpclient;
import java.io.IOException;
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 ResponseStatusTest {
/**
* @param args
*/
public static void main ( String [] args ) {
HttpClient httpclient = new DefaultHttpClient () ;
HttpGet httpget = new HttpGet ( "http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOG" ) ;
System.out.println ( "Requesting : " + httpget.getURI ()) ;
try {
HttpResponse response = httpclient.execute ( httpget ) ;
System.out.println ( "Protocol : " + response.getProtocolVersion ()) ;
System.out.println ( "Status code : " + response.getStatusLine () .getStatusCode ()) ;
System.out.println ( "Status line : " + response.getStatusLine ()) ;
System.out.println ( "\n\nResponse : " ) ;
if ( response.getEntity () != null ) {
System.out.println ( EntityUtils.toString ( response.getEntity ())) ;
}
} catch ( ClientProtocolException e ) {
e.printStackTrace () ;
} catch ( IOException e ) {
e.printStackTrace () ;
} finally {
httpclient.getConnectionManager () .shutdown () ;
}
}
}
It gives the following output,
Requesting : http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOG
Protocol : HTTP/1.1
Status code : 200
Status line : HTTP/1.1 200 OK
Response :
// [
{
"id": "694653"
,"t" : "GOOG"
,"e" : "NASDAQ"
,"l" : "604.33"
,"l_cur" : "604.33"
,"s": "0"
,"ltt":"2:39PM EST"
,"lt" : "Mar 9, 2:39PM EST"
,"c" : "-2.81"
,"cp" : "-0.46"
,"ccol" : "chr"
}
]