Apache httpcomponents Client 4.0 has been released for a long, httpclient project moved from the Commons subproject to the Httpcomponents Sub project, httpclient3.1 and httpcilent4.0 can not do code backwards compatibility, upgrade more cumbersome. I was doing a project to find time to study, wrote a set of 3.1 and 4.0 of the code, not to be exhaustive, but easy to understand. If your code is used in a real project, you also need to consider issues such as proxies, Header, exception handling, and so on.
The Http get method gets the www.g.cn source:
Import java.io.IOException; Import org.apache.commons.httpclient.HttpException; Import Org.apache.commons.httpclient.HttpStatus; Import Org.apache.commons.httpclient.methods.GetMethod; Import org.apache.http.client.ClientProtocolException; Import Org.apache.http.client.methods.HttpGet; Import Org.apache.http.impl.client.BasicResponseHandler; Import org.apache.http.impl.client.DefaultHttpClient; public class Getsample {/** * @param args * @throws ioexception * @throws httpexception/public static void main (String [] args throws HttpException, ioexception {String url = ' http://www.g.cn/'; System.out.println (URL); System.out.println ("Visit Google using Apache commons-httpclient 3.1:"); System.out.println (Get3 (URL)); System.out.println ("Visit Google using Apache httpcomponents Client 4.0:"); System.out.println (Get4 (URL)); /** use the Apache Commons-httpclient 3.1,get method to access Web pages/public static String get3 (String url) throws HttpException, IOException {org.apache.commons.httpclient.HttpClientHttpClient = new Org.apache.commons.httpclient.HttpClient (); GetMethod GetMethod = new GetMethod (URL); try {if (Httpclient.executemethod (GetMethod)!= httpstatus.sc_ok) {System.err.println ("Method failed:" + getmethod.get Statusline ()); return getmethod.getresponsebodyasstring (); finally {getmethod.releaseconnection ();}} /** uses the Apache httpcomponents Client 4.0,get method to access the Web page/public static String get4 (String url) throws Clientprotocolexception, IOException {org.apache.http.client.HttpClient client = new Defaulthttpclient (); HttpGet httpget = new HttpGet (URL); try {return Client.execute (HttpGet, New Basicresponsehandler ());} finally {Client.getconnectionmanager (). shutdown ();} } }