1 package sedion.wq.MonitorWechattest; 2 3 import org.apache.http.HttpEntity; 4 import org.apache.http.HttpResponse; 5 import org.apache.http.HttpStatus; 6 import org.apache.http.client.HttpClient; 7 import org.apache.http.client.methods.HttpGet; 8 import org.apache.http.impl.client.DefaultHttpClient; 9 import org.apache.http.util.EntityUtils; 10 11 /** 12 * 模拟微信浏览器请求 13 */ 14 public class MonitorWechatBrowser { 15 public static void main(String[] args) { 16 String url = "http://www.where is your need.com"; 17 String userAgent="Mozilla/5.0 (Linux; U; Android 4.1.2; zh-cn; GT-I9300 Build/JZO54K) "+ 18 "AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 MicroMessenger/5.2.380"; 19 String html = getHttpClientHtml(url, "UTF-8"); 20 System.out.println(html); 21 } 22 23 24 /** 25 * 根据URL得到全部的html信息 26 */ 27 public static String getHttpClientHtml(String url,String code,String userAgent) { 28 String html = null; 29 HttpClient httpClient = new DefaultHttpClient();// 建立httpClient对象 30 HttpGet httpget = new HttpGet(url);// 以get方式请求该URL 31 httpget.setHeader("User-Agent",userAgent ); 32 try { 33 // 获得responce对象 34 HttpResponse responce = httpClient.execute(httpget); 35 // 返回码 36 int returnCode = responce.getStatusLine().getStatusCode(); 37 // 是200证实正常 其余就不对 38 if (returnCode== HttpStatus.SC_OK) { 39 // 得到相应实体 40 HttpEntity entity = responce.getEntity(); 41 if (entity != null) { 42 html = new String(EntityUtils.toString(entity));// 得到html源代码 43 } 44 } 45 } catch (Exception e) { 46 System.out.println("出现出现异常"); 47 e.printStackTrace(); 48 } finally { 49 httpClient.getConnectionManager().shutdown(); 50 } 51 return html; 52 } 53 }
本文只是自个人一个总结,若是对你有所帮助是个人荣幸,文章不妥之处但愿指正,大神勿喷,请经过留言或关注微信公众账号codenewbie来支持小八哥!如有不妥之处,欢迎指点。html
转帖请注明本文出自小八哥的博客(http://www.cnblogs.com/Codenewbie),请尊重他人的辛勤劳动成果,谢谢!html5