分享

如何设置Fiddler来拦截Java代码发送的HTTP请求,进行各种问题排查

 汪子熙 2019-12-22

我们使用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://:9002/rest/v2/electronics/users/jerry.wang@sap.com";
        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开发者工具的角色。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":


    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多