參考資料html
默認狀況下Fiddler是不能監聽Java HttpURLConnection上的HTTP請求的。緣由容易理解,Fiddler能監聽瀏覽器的HTTP請求是由於它啓動一個代理服務器,瀏覽器經過這個代理服務器上網,但HttpURLConnection默認不使用該代理。java
Fiddler 官方給出的解決方法是啓動Java程序時設置代理,例如:瀏覽器
java -DproxySet=true -DproxyHost=127.0.0.1 -DproxyPort=8888 Main2
stackoverflow上有人提供了另外一種方法:服務器
// set http proxy System.setProperty("http.proxyHost", "localhost"); System.setProperty("http.proxyPort", "8888"); // set https proxy System.setProperty("https.proxyHost", "localhost"); System.setProperty("https.proxyPort", "8888");
使用如下代碼訪問 http://www.163.com/ 測試,以上兩種方法均可行測試
public class Main2 { public static void main(String[] args) throws Exception { // set http proxy System.setProperty("http.proxyHost", "localhost"); System.setProperty("http.proxyPort", "8888"); // set https proxy System.setProperty("https.proxyHost", "localhost"); System.setProperty("https.proxyPort", "8888"); doRequest(); } private static void doRequest() { HttpURLConnection conn = null; try { URL url = new URL("http://www.163.com/"); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setDoInput(true); conn.setDoOutput(false); conn.setRequestMethod("GET"); // 設定請求方式 conn.connect(); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { // System.out.println(line); } reader.close(); // 判斷是否正常響應數據 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { System.out.println("錯誤響應碼 " + conn.getResponseCode()); } } catch (Exception e) { System.out.println("異常!"); } finally { if (conn != null) { conn.disconnect(); // 中斷鏈接 } } } }