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

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的证书导入到信任证书库。

转载于:https://my.oschina.net/guyongquan/blog/497656

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值