ITPub博客

首页 > 应用开发 > IT综合 > 如何设置Fiddler来拦截Java代码发送的HTTP请求,进行各种问题排查

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

原创 IT综合 作者:i042416 时间:2019-12-29 12:35:14 0 删除 编辑

我们使用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/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的原创文章,请关注公众号"汪子熙":


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/24475491/viewspace-2671133/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
测试

注册时间:2018-01-20

  • 博文量
    3822
  • 访问量
    1981774