码迷,mamicode.com
首页 > Web开发 > 详细

给HttpClient配置代理以使用Fiddler拦截发送的请求

时间:2015-08-27 08:21:53      阅读:602      评论:0      收藏:0      [点我收藏+]

标签:

import java.io.File;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class ProxyHttpClient {

    public static void main(String[] args) throws Exception {
        FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("file:" + new File("./ProxyHttpClient.xml").getCanonicalPath());
        try {
            HttpClient client = context.getBean(HttpClient.class);
            HttpResponse response = client.execute(new HttpGet("http://cn.bing.com/"));
            String contentType = response.getFirstHeader("Content-Type").getValue();
            System.out.println(IOUtils.toString(response.getEntity().getContent(), contentType.substring(contentType.lastIndexOf(‘=‘) + 1)));
        } finally {
            context.close();
        }
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
	<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClients" factory-method="custom">
		 <property name="proxy">
			<bean class="org.apache.http.HttpHost">
				<constructor-arg index="0" value="127.0.0.1"/>
				<constructor-arg index="1" value="8888"/><!--8888是我机器上Fiddler代理服务器的端口号 -->
			</bean>
		</property>
	</bean>
	<bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build" destroy-method="close"></bean>
</beans>

如果要拦截https请求,那么需要把Fiddler的证书导入到信任证书库。

给HttpClient配置代理以使用Fiddler拦截发送的请求

标签:

原文地址:http://my.oschina.net/guyongquan/blog/497656

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!