1 http數據包的組成
作爲一個去模擬發包的程序猿,在實際發包之前,你首先要知道的是,數據包中你需要關注的東西。
1.1 url
這個不用多說,就是發出去的請求
1.2 請求類型
常見的如get put delete post 等
1.3 請求頭
包含一些請求頭字段 比如爬蟲中經常用到的 User-Agent等
1.4 請求體
主要是post 請求中附帶的參數,如提交的表單等
1.5 Cookie
瀏覽器緩存
對於兩個Http請求,如果上面的5個部分是完全相等的,他們在服務器看來就是等價的。所以要完成模擬發包,就要能夠設置以上5個部分。下面來看具體操作
2 如何獲取httpclient 相關jar包
可以去http://hc.apache.org/downloads.cgi 下載最新的jar包
或者使用maven 構建,maven的相關配置爲
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
3 常用的動能
3.1 構建不同的請求
String url="https://mp.csdn.net/";
//構建get請求
HttpGet httpGet=new HttpGet(url);
//構建post請求
HttpPost httpPost=new HttpPost(url);
//put 請求
HttpPut httpPut=new HttpPut(url);
//....
3.2 設置http 頭參數 //設置 請求頭參數
httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/60.0");
httpGet.setHeader("Host","mp.csdn.net");
3.3設置請求體
//設置請求參數
//設置請求參數通過HttpEntity
//1設置formdata;
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("a", "b"));
HttpEntity formData = null;
try {
formData = new UrlEncodedFormEntity(paramList, "utf-8"); //處理編碼
} catch (Exception e) {
e.printStackTrace();
}
httpPost.setEntity(formData);
//2 設置jsondata json字符串
StringEntity stringEntity = new StringEntity("{a:b}","utf-8");
httpPost.setEntity(stringEntity);
3.5設置cookie 及發送請求
//3設置cookie 及發送請求
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
BasicClientCookie cookie = new BasicClientCookie("co", "ba");
cookie.setDomain(url);
cookieStore.addCookie(cookie);
HttpResponse httpResponse=null;
try {
httpResponse= httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
3.6獲取返回結果//獲取返回http 狀態碼
httpResponse.getStatusLine().getStatusCode();
//獲取返回結果
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + NL);
}
bufferedReader.close();
String res= sb.toString();
} catch (IOException e) {
e.printStackTrace();
}