日期:2014-05-16 浏览次数:20781 次
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)); } /** 使用Apache commons-httpclient 3.1,GET方法访问网页 */ public static String get3(String url) throws HttpException, IOException { org.apache.commons.httpclient.HttpClient httpClient = 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.getStatusLine()); } return getMethod.getResponseBodyAsString(); } finally { getMethod.releaseConnection(); } } /** 使用Apache HttpComponents Client 4.0,GET方法访问网页 */ 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(); } } }