最近在弄着抓去网站数据解析的工作,其中,使用到GET和POST方法获取html数据。
使用GET方式:
/**
* 使用get方式获取html数据
*
* @param strURL(需要访问的网站)
* @return
* @throws Exception
*/
public String getHTML(String strURL) throws Exception {
//创建浏览器
HttpClient httpClient = HttpClients.createDefault();
String html = null;
//预防网址链接中包含特殊字符,将url转为uri
URL url = new URL(strURL);
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
url.getQuery(), null);
//使用get方式
HttpGet request = new HttpGet(uri);
HttpResponse response;
try {
//连接网址获取返回的数据
response = httpClient.execute(request);
//将返回的数据按照gbk的方式编码
html = EntityUtils.toString(response.getEntity(), "GBK");
} catch (IOException e) {
e.printStackTrace();
}
//断开连接
request.abort();
//返回网址所发挥的html数据
return html;
}使用该方法便可以获取得到网站所发挥的html数据。
使用POST方式:
/**
* 使用post方式获取html数据
*
* @param libraryUrl(需要访问的网站)
* @param params(需要传入的参数)
* @return
* @throws Exception
*/
public String postHTML(String strURL, List params)
throws Exception {
//创建浏览器
HttpClient httpClient = HttpClients.createDefault();
String html = null;
//预防网址链接中包含特殊字符,将url转为uri
URL url = new URL(strURL);
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
url.getQuery(), null);
//使用POST方式
HttpPost request = new HttpPost(uri);
//将参数封装进UrlEncodedFormEntity中
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
request.setEntity(entity);
HttpResponse response;
try {
//连接网址获取返回的数据
response = httpClient.execute(request);
//将返回的数据按照gbk的方式编码
html = EntityUtils.toString(response.getEntity(), "GBK");
} catch (IOException e) {
e.printStackTrace();
}
//断开连接
request.abort();
//返回网址所发挥的html数据
return html;
}
其中,参数params的封装可以参照以下方式:
List params = new ArrayList();
//以键值对的方式存储
params.add(new BasicNameValuePair("format", "hitcount"));