在IntelliJ idea中使用fiddler捕獲Web請求
阿新 • • 發佈:2019-01-05
遇到的一個通用的需求就是用java程式來寫get或post程式時如果能夠捕獲http請求和響應的過程,那會是很有幫助的。
通過fiddler可以實現以上的需求。
步驟2:在java程式中使用
模擬get請求的靜態方法
/**
* 模擬get請求伺服器資源
* @param strUrl
*/
public static void mimicGet(String strUrl) {
//使程式通過代理伺服器( proxy server )訪問Web
//代理伺服器接收到從本地客戶端到遠端伺服器的請求。代理伺服器向遠端伺服器發出請求,再將結果轉發回本地客戶端。
//此處代理伺服器就是fiddler
//在Java程式碼中呼叫System.setProperty ()
//使用純粹的HTTP代理,將http.proxyHost設定為代理伺服器的域名或IP地址
System.setProperty("http.proxyHost", "127.0.0.1");
System.setProperty("https.proxyHost", "127.0.0.1");
System.setProperty("http.proxyPort", "8888");
System.setProperty("https.proxyPort" , "8888");
try {
URL u = new URL(encodeUrl(strUrl));
try {
try (InputStream in = new BufferedInputStream(u.openStream())) {
InputStreamReader theHTML = new InputStreamReader(in);
int c;
while ((c = theHTML.read()) != -1) {
System.out.print((char) c);
}
}
} catch (MalformedURLException ex) {
System.err.println(ex);
} catch (IOException ex) {
System.err.println(ex);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* 將queryString轉換為utf-8編碼的16位ASCII字串
* https://www.baidu.com/search?wd=木&rsv_spt=1
* @param queryString 為wd=木&rsv_spt=1
* @return
*/
public static String encodeQueryString(String queryString) {
StringBuilder sb = new StringBuilder();
String[] split = queryString.split("&");
for (String str : split) {
String[] split1 = str.split("=");
try {
sb.append(URLEncoder.encode(split1[0], "utf-8"));
sb.append("=");
sb.append(URLEncoder.encode(split1[1], "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
sb.append("&");
}
String s = sb.toString();
return s.substring(0,s.length() - 1);
}
/**
* 將url字串轉換為utf-8編碼的16位ASCII字串
* @param urlStr
* @return
*/
public static String encodeUrl(String urlStr) {
int index = urlStr.lastIndexOf("?")+1;
return urlStr.substring(0, index) + encodeQueryString(urlStr.substring(index));
}
測試方法
@Test
public void testMimicGet() {
String str = "http://www.baidu.com/s?wd=木";
WebUtil.mimicGet(str);
}
Fiddler成功捕獲