package org.jshand.utils.http;
import java.io.FileOutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;
/**
* TODO(用一句話描述該文件的作用)
*
* @title: HttpClientDemo.java
* @author zhangjinshan-ghq
* @date 2014-6-11 14:59:04
*/
public class HttpClientDemo
{
/**
* The main method.
*
* @param args the arguments
* @throws Exception the exception
*/
public static void main(String[] args) throws Exception
{
getResoucesByLoginCookies();
}
/**
* 根據(jù)登錄Cookie獲取資源
* 一切異常均未處理,需要酌情檢查異常
*
* @throws Exception
*/
private static void getResoucesByLoginCookies() throws Exception
{
HttpClientDemo demo = new HttpClientDemo();
String username = "XXXXXXXXX";// 登錄用戶
String password = "XXXXXXXX";// 登錄密碼
// 需要提交登錄的信息
String urlLogin = "http://www.iteye.com/login?name=" + username + "&password=" + password;
// 登錄成功后想要訪問的頁面 可以是下載資源 需要替換成自己的iteye Blog地址
String urlAfter = "http://314649444.iteye.com/";
DefaultHttpClient client = new DefaultHttpClient(new PoolingClientConnectionManager());
/**
* 第一次請求登錄頁面 獲得cookie
* 相當(dāng)于在登錄頁面點(diǎn)擊登錄,此處在URL中 構(gòu)造參數(shù),
* 如果參數(shù)列表相當(dāng)多的話可以使用HttpClient的方式構(gòu)造參數(shù)
* 此處不贅述
*/
HttpPost post = new HttpPost(urlLogin);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
CookieStore cookieStore = client.getCookieStore();
client.setCookieStore(cookieStore);
/**
* 帶著登錄過的cookie請求下一個(gè)頁面,可以是需要登錄才能下載的url
* 此處使用的是iteye的博客首頁,如果登錄成功,那么首頁會顯示【歡迎XXXX】
*
*/
HttpGet get = new HttpGet(urlAfter);
response = client.execute(get);
entity = response.getEntity();
/**
* 將請求結(jié)果放到文件系統(tǒng)中保存為 myindex.html,便于使用瀏覽器在本地打開 查看結(jié)果
*/
String pathName = "d:\\myindex.html";
writeHTMLtoFile(entity, pathName);
}
/**
* Write htmL to file.
* 將請求結(jié)果以二進(jìn)制形式放到文件系統(tǒng)中保存為.html文件,便于使用瀏覽器在本地打開 查看結(jié)果
*
* @param entity the entity
* @param pathName the path name
* @throws Exception the exception
*/
public static void writeHTMLtoFile(HttpEntity entity, String pathName) throws Exception
{
byte[] bytes = new byte[(int) entity.getContentLength()];
FileOutputStream fos = new FileOutputStream(pathName);
bytes = EntityUtils.toByteArray(entity);
fos.write(bytes);
fos.flush();
fos.close();
}
}
第二種方式:在httpclient里配置cookie的管理方式,自動管理cookie
//創(chuàng)建自動管理cookie的httpClient
// RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
// CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();