抓jsoup_01_方案代码
1、方案选择:
1.1、HttpClient库 获取 原始的 json数据
1.2、JSON库 取得 我们需要的HTML内容
1.3、使用 jsoup 解析 我们取得的HTML内容
2、不直接使用 jsoup,原因:
2.1、它会自动补全 HTML的头和尾(<html/><body/>等),jsoup中没有这个
处理方法:手动指定 Parser.xmlParser()
2.2、如果属性 没有用 2个双引号包裹起来,它会将 这2个双引号补全... 这个功能 在jsoup里面没法关闭...
3、示例代码:
3.1、工具类
package z_utils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class TzHttpClient { public static void main(String[] args) throws Exception { String strRtn = PostZ( "http://ajax.mianbao99.com/vod-showlist-id-8-order-time-c-3719-p-2.html", null, true); System.out.println(strRtn); } // *** @SuppressWarnings("deprecation") public static String PostZ(String _strUrl, String _strParam, boolean _bNeedResponse) throws Exception { //post请求返回结果 DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost method = new HttpPost(_strUrl); if (null != _strParam) { //解决中文乱码问题 StringEntity entity = new StringEntity(_strParam, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); method.setEntity(entity); } HttpResponse result = httpClient.execute(method); /**请求发送成功,并得到响应**/ if (result.getStatusLine().getStatusCode() == 200) { if (! _bNeedResponse) return null; String str = EntityUtils.toString(result.getEntity()); //System.out.println(str); return str; } return null; } @SuppressWarnings("deprecation") public static String GetZ(String _strUrl) throws Exception { DefaultHttpClient client = new DefaultHttpClient(); //发送get请求 HttpGet request = new HttpGet(_strUrl); HttpResponse response = client.execute(request); /**请求发送成功,并得到响应**/ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**读取服务器返回过来的json字符串数据**/ String strResult = EntityUtils.toString(response.getEntity()); //System.out.println(strResult); return strResult; } System.out.println("get请求提交失败:" + _strUrl); return null; } }
3.2、测试 功能代码
package test; import org.jsoup.Connection; ///import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.*; import org.jsoup.parser.Parser; import net.sf.json.*; import z_utils.TzHttpClient; public class Ttest01 { public static void main(String[] args) throws Exception { String strHtml = TzHttpClient.GetZ("http://ajax.mianbao99.com/vod-showlist-id-8-order-time-c-3719-p-2.html"); JSONObject jsoupObj = JSONObject.fromObject(strHtml); if (! jsoupObj.containsKey("ajaxtxt")) return; // Connection conn = null; // conn.parser(Parser.xmlParser()); String strAjaxtxt = jsoupObj.getString("ajaxtxt"); Document doc = Jsoup.parse(strAjaxtxt, "", Parser.xmlParser()); System.out.println(doc.html()); } }
4、