前两天学习HttpClient,大概理解了HttpClient的作用,后来得知httpClient也能做页面静态化,就在在百度上搜关于httpClient如何实现页面静态化,但搜到的结果全部都是很久以前的httpClient版本做的页面静态化,于是我便根据自己的理解,用HttpClient 4.5 做了一个页面静态化的例子,今天就在这里跟大家分享一下
httpClient实现页面静态化,需要用到它的get方法来获取到网页内的数据,再将页进行静态化
下面是httpClient的get方法的一个例子
/**
* @author
* @date 2016年8月18日 下午3:26:56
* @return_type void
* 发送get请求,读取网页内数据
*/
@Test
public void get(){
CloseableHttpClient httpClient=HttpClients.createDefault();
// 创建httpget.
HttpGet httpget = new HttpGet("http://localhost:8080/hotel/reserve/reserveList.action");
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
HttpResponse response = null;
try {
response = httpClient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
System.out.println("--------------------------------------");
if (entity != null) {
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity,"utf-8"));
}
} catch (org.apache.http.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
了解了get方法之后,我们就可以利用get方法来实现httpClient页面静态化了
/**
* @author wzg
* @date 2016年8月22日 下午5:16:48
* @project first
* @package com.wzg.util
*/
public class Demo {
public boolean test(String url,String htmlPage){
//创建默认的httpClient实例
CloseableHttpClient httpClient=HttpClients.createDefault();
// 创建httpget.
HttpGet get = new HttpGet(url);
try {
//执行get请求
CloseableHttpResponse response = httpClient.execute(get);
//获取响应实体
HttpEntity entity = response.getEntity();
//定义BufferedReader输入流来读取URL的响应
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String pageContent="";
//逐行读取数据
while(true){
String line = br.readLine();
if(line == null){
break;
}else{
pageContent+=line;
pageContent+="\n";
}
}
//创建字符输出流
FileWriter writer = new FileWriter(htmlPage);
PrintWriter fout = new PrintWriter(writer);
fout.print(pageContent);
fout.close();
} catch (IOException e) {
System.out.println("IOException");
return false;
}
return true;
}
public static void main(String[] args) {
Demo demo = new Demo();
demo.test("http://localhost:8080/hotel/admin/out.action", "D:/a.html");
System.out.println("已生成静态页面");
}
}