页面静态化-http get请求获取页面内容代码
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 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。