【文件属性】:
文件名称:java 爬网 程序 示例
文件大小:5KB
文件格式:RAR
更新时间:2014-08-07 05:37:12
java 爬网 程序 示例
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetNetHtml {
public static String createhttpClient(String url, String param) {
HttpClient client = new HttpClient();
String response = null;
String keyword = null;
PostMethod postMethod = new PostMethod(url);
// try {
// if (param != null)
// keyword = new String(param.getBytes("gb2312"), "ISO-8859-1");
// } catch (UnsupportedEncodingException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
// NameValuePair[] data = { new NameValuePair("keyword", keyword) };
// // 将表单的值放入postMethod中
// postMethod.setRequestBody(data);
// 以上部分是带参数抓取,我自己把它注销了.大家可以把注销消掉研究下
try {
int statusCode = client.executeMethod(postMethod);
response = new String(postMethod.getResponseBodyAsString()
.getBytes("ISO-8859-1"), "gb2312");//这里要注意下 gb2312要和你抓取网页的编码要一样
String p = response.replaceAll("\\&[a-zA-Z]{1,10};", "")
.replaceAll("<[^>]*>", "");//去掉网页中带有html语言的标签
System.out.println(p);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
// 第二种方法
// 这种方法是JAVA自带的URL来抓取网站内容
public String getPageContent(String strUrl, String strPostRequest,
int maxLength) {
// 读取结果网页
StringBuffer buffer = new StringBuffer();
System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
System.setProperty("sun.net.client.defaultReadTimeout", "5000");
try {
URL newUrl = new URL(strUrl);
HttpURLConnection hConnect = (HttpURLConnection) newUrl
.openConnection();
// POST方式的额外数据
if (strPostRequest.length() > 0) {
hConnect.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(hConnect
.getOutputStream());
out.write(strPostRequest);
out.flush();
out.close();
}
/*部分删节,请下载细看!!*/
public static void main(String[] args) {
String url = "http://www.liuzm.com";
String keyword = "刘志猛博客";
GetNetHtml p = new GetNetHtml();
String response = p.createhttpClient(url, keyword); // 第一种方法
// p.getPageContent(url, "post", 100500);//第二种方法
}
}
【文件预览】:
PreDealWith
----bin()
--------Test.class(237B)
--------GetNetHtml.class(3KB)
----.settings()
--------org.eclipse.jdt.core.prefs(629B)
----src()
--------Test.java(28B)
--------GetNetHtml.java(4KB)
----.project(387B)
----.classpath(555B)