# 模擬http請求
如何模擬一個http請求,在上一個章節中已經對http協議有了一個簡單的理解。模擬一個http請求,就是通過代碼,模擬一個瀏覽器做的事情,也可以理解成模擬一個用戶在做的事情,爬蟲就是一個不理智的用戶,他在瘋狂的通過一個瀏覽器點擊呈現在頁面上他想要的鏈接。
###通過firebug工具查看一個http請求
1:安裝firbug插件
firbug插件只是其中的一個查看瀏覽器http請求的方式,也可以通過其他的模式去查看,工具有很多,不用太局限與形式,這里只是用firebug做一個例子。
2:發送請求https://www.baidu.com
3:查看firbug,觀察http請求參數

###代碼模擬http請求
```/**
*
* @param URL
* @param defaultEncoding
* @param timeOut
* @return String[] http內容
*/
public static final String getUrlString(URL url, String defaultEncoding, int timeOut) {
boolean gzip = false;
InputStream in = null;
String location ="";
HttpURLConnection con = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(timeOut);
con.setConnectTimeout(timeOut);
// 設置HTTP request Header
// 設置UA (關于useragent的具體意義,可自行百度或者谷歌,在這里可以簡單的理解成,UA標示是用于模擬一個真實用戶的一個標示)
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10");
con.setRequestProperty("Keep-Alive", "115");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
// 以上參數就是用于模擬一個 http請求,使用firebug,可以查看一個http請求的時候的具體請求頭跟返回的頭
if ((gzip) && (Math.random() < 0.3D)) {
con.setRequestProperty("Accept-Encoding", "gzip");
}
// 記錄請求時間
long starttime = System.currentTimeMillis();
con.connect();
// 獲取http請求返回碼
int code = con.getResponseCode();
int length = con.getContentLength();
if (length >= 0) {
}
// 獲取http請求的返回內容類型
String encoding2 = con.getHeaderField("Content-Type");
if (encoding2 != null) {
int index;
if ((index = encoding2.indexOf("charset=")) > 0)
encoding2 = encoding2.substring(index + "charset=".length()).replace('"', ' ').replace('\'', ' ').trim();
else
encoding2 = defaultEncoding;
}
// 如果為404 返回內容也沒有意義
if(code ==404){
return "";
}
if (code != 404) {
in = new BufferedInputStream(con.getInputStream());
}
if (in == null){
return null;
}
location = con.getHeaderField("Location");
if(location==null){
location="";
}
// 判斷頁面是否壓縮傳輸
//關于gzip壓縮的理解,請參考以下博文
//http://kb.cnblogs.com/page/163781/
String contentencoding = con.getHeaderField("Content-Encoding");
if ((gzip) && ("gzip".equals(contentencoding))) {
System.out.println("gzipped");
in = new GZIPInputStream(in);
}
ByteArrayOutputStream urlData = new ByteArrayOutputStream();
byte[] buf2 = new byte[1024];
int n;
while ((n = in.read(buf2)) >= 0) {
if (urlData.size() > 2097152) {
if (length < 0)
return null;
}
urlData.write(buf2, 0, n);
}
if (length < 0){
}
String str1 = null;
if (encoding2 != null) {
try {
str1 = urlData.toString(encoding2);
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
in = null;
}
if (con != null) {
try {
con.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
con = null;
}
return str1;
} catch (UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException detected: " + e.getMessage());
str1 = urlData.toString();
if (in != null) {
try {
in.close();
} catch (Exception e1) {
e1.printStackTrace();
}
in = null;
}
if (con != null) {
try {
con.getInputStream().close();
} catch (Exception e2) {
e2.printStackTrace();
}
con = null;
}
return str1;
}
}
return str1;
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
if (con != null)
try {
InputStream err = con.getErrorStream();
if (err != null) {
err.close();
err = null;
}
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
in = null;
}
if (con != null) {
try {
con.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
con = null;
}
}
return null;
}```
資料參考 :
> http://kb.cnblogs.com/page/163781/
http協議之壓縮
- Introduction
- 爬蟲相關技能介紹
- 爬蟲簡單介紹
- 爬蟲涉及到的知識點
- 爬蟲用途
- 爬蟲流程介紹
- 需求描述
- Http請求處理
- http基礎知識介紹
- http狀態碼
- httpheader
- java原生態處理http
- URL類
- 獲取URL請求狀態
- 模擬Http請求
- apache httpclient
- Httpclient1
- httpclient2
- httpclient3
- httpclient4
- httpclient5
- httpclient6
- okhttp
- OKhttp使用教程
- 技術使用
- java執行javascript
- 網頁解析
- Xpath介紹
- HtmlCleaner
- HtmlCleaner介紹
- HtmlCleaner使用
- HtmlParser
- HtmlParser介紹
- Jsoup
- 解析和遍歷一個HTML文檔
- 解析一個HTML字符串
- 解析一個body片斷
- 從一個URL加載一個Document
- 從一個文件加載一個文檔
- 使用DOM方法來遍歷一個文檔
- 使用選擇器語法來查找元素
- 從元素抽取屬性,文本和HTML
- 處理URLs
- 示例程序 獲取所有鏈接
- 設置屬性的值
- 設置一個元素的HTML內容
- 消除不受信任的HTML (來防止XSS攻擊)
- 正則表達式
- elasticsearch筆記
- 下載安裝elasticsearch
- 檢查es服務健康