1 import org.apache.http.HttpEntity; 2 import org.apache.http.HttpException; 3 import org.apache.http.HttpResponse; 4 import org.apache.http.client.HttpClient; 5 import org.apache.http.client.methods.HttpGet; 6 import org.apache.http.client.methods.HttpRequestBase; 7 import org.apache.http.impl.client.HttpClients; 8 import org.apache.http.protocol.BasicHttpContext; 9 import org.apache.http.protocol.HttpContext; 10 import org.apache.http.util.EntityUtils; 11 12 /** 13 * 页面静态化,通过http get请求获取页面内容 14 * 注意:要引入common-logging、httpcore、httpclient的jar包 15 */ 16 public class PageStatic 17 { 18 public static void main(String[] args) 19 { 20 HttpClient client = HttpClients.createDefault(); 21 String url = "http://fanyi.youdao.com/"; 22 HttpRequestBase http = new HttpGet(url); 23 HttpContext context = new BasicHttpContext(); 24 try 25 { 26 HttpResponse response = client.execute(http, context); 27 int statusCode = response.getStatusLine().getStatusCode(); 28 29 switch (statusCode) 30 { 31 case 200: 32 case 400:// 业务异常 33 break; 34 default: 35 throw new HttpException(url + " Status Code:" + statusCode); 36 } 37 38 HttpEntity entity = response.getEntity(); 39 String reStr = EntityUtils.toString(entity); 40 System.out.println(reStr); 41 } 42 catch (Exception e) 43 { 44 System.out.println(e.toString()); 45 } 46 } 47 48 }
时间: 2024-10-10 00:24:26