天天看點

如何設定Fiddler來攔截Java代碼發送的HTTP請求,進行各種問題排查

我們使用Java的RestTemplate或者Apache的HTTPClient程式設計的時候,經常遇到需要跟蹤Java

代碼發送的HTTP請求明細的情況。和javascript代碼在浏覽器裡發送請求可以通過Chrome開發者工具友善地跟蹤一樣,對于Java代碼發送的網絡請求,我們也可以使用工具Fiddler來監控。

打開Fiddler,在connections面闆裡找到Fiddler監聽的端口号8888:

如果是使用Apache的HTTPClient進行網絡請求發送,代碼如下:

使用HttpHost設定請求代理:

private static void downloadCommerce(){
        HttpHost proxy = new HttpHost("localhost", 8888, "http");
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        CloseableHttpClient client= HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        String url = "https://jerrywang.com:9002/rest/v2/electronics/users/[email protected]";
        String token = "test";
        HttpGet get = new HttpGet(url);
        get.setHeader("Authorization", "Bearer " + token);
            try {
                HttpResponse response = client.execute(get);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
                System.out.println("url: " + result);
            } catch (Exception e){
                e.printStackTrace();
            }
    }           

執行Java應用,然後到Fiddler裡,看到了監控到的HTTP請求各種明細,比如Java代碼裡寫死的OAuth 2的認證token test:

Java代碼收到的伺服器端傳回的錯誤消息:

這個錯誤消息在Fiddler裡當然也是可以看到的:

在這種場景裡,Fiddler扮演的就是類似Chrome開發者工具的角色。

本文來自雲栖社群合作夥伴“汪子熙”,了解相關資訊可以關注微信公衆号"汪子熙"。