httpclient4 小例子

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
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;

public class HttpClientTest {

	public static void main(String[] args) throws ClientProtocolException,
			IOException {
		 HttpClient httpclient = new DefaultHttpClient();
		 // Prepare a request object
		 HttpGet httpget = new HttpGet("*********");
		 httpget.addHeader("accept-encoding", "gzip,deflate"); 
		 httpget.addHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)"); 
		 // Execute the request
		 HttpResponse response = httpclient.execute(httpget);
		 // Examine the response status
		 System.out.println(response.getStatusLine());
		 // Get hold of the response entity
		 HttpEntity entity = response.getEntity();
		 // to worry about connection release
		 if (entity != null) {
		     InputStream instream = entity.getContent();
		     try {
		         BufferedReader reader = new BufferedReader(
		                 new InputStreamReader(instream));
		         // do something useful with the response
		         String htmlStr;
		         while((htmlStr = reader.readLine()) != null ){
		        	 System.out.println(htmlStr);
		         }
		        // System.out.println(reader.readLine());
		     } catch (IOException ex) {
		         // In case of an IOException the connection will be released
		         // back to the connection manager automatically
		         throw ex;

		     } catch (RuntimeException ex) {
		         // In case of an unexpected exception you may want to abort
		         // the HTTP request in order to shut down the underlying
		         // connection and release it back to the connection manager.
		         httpget.abort();
		         throw ex;
		     } finally {
		         // Closing the input stream will trigger connection release
		         instream.close();
		     }
		     // When HttpClient instance is no longer needed,
		     // shut down the connection manager to ensure
		     // immediate deallocation of all system resources
		     httpclient.getConnectionManager().shutdown();
		 }
	}
}

你可能感兴趣的:(httpclient)