HttpClient实现白名单全局代理

试用于httpClient 4.*,自定义一个routePlanner,判断请求的目标地址就可以了

package com.zhutougg.demo;

import java.util.regex.Matcher;  
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;  
import org.apache.http.HttpException;  
import org.apache.http.HttpHost;  
import org.apache.http.HttpRequest;  
import org.apache.http.client.methods.CloseableHttpResponse;  
import org.apache.http.client.methods.HttpGet;  
import org.apache.http.conn.routing.HttpRoute;  
import org.apache.http.conn.routing.HttpRoutePlanner;  
import org.apache.http.impl.client.CloseableHttpClient;  
import org.apache.http.impl.client.HttpClients;  
import org.apache.http.protocol.HttpContext;  
import org.apache.http.util.EntityUtils;

public class HttpClientProxy2 {  
    //自定义代理规则 
    static HttpRoutePlanner routePlanner = new HttpRoutePlanner(){
        @Override
        public HttpRoute determineRoute(HttpHost target, HttpRequest request,
                HttpContext context) throws HttpException {
            //设置白名单 ,若匹配成功,则不走代理
            String regex="10.*.*.*";//匹配规则 ,如果有别的请求不要求走代理的话,可以加到正则里面
            Matcher m=Pattern.compile(regex).matcher(target.getHostName());  
            if(m.find()){
                return new HttpRoute(target);
            }
            //匹配不成功,通过代理请求,请修改成公司内网的代理IP和端口
            return new HttpRoute(target,null,new HttpHost("118.114.77.47",8080),"https".equalsIgnoreCase(target.getSchemeName()));
        }
    };

    static CloseableHttpClient httpclient = HttpClients.custom().setRoutePlanner(routePlanner).build();

    public static void main(String[] args) throws Exception {
        proxy();
    }

    private static void proxy() throws Exception {
        // 请求地址
        HttpGet httpGet = new HttpGet("http://www.zhutougg.com/xxxxxxx");
        // 设置相关请求头
        httpGet.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
        CloseableHttpResponse response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            System.out.println("response: " + EntityUtils.toString(entity));
        }
        httpclient.close();
    }
}

欢迎大家加入小密圈,一起交流进步

zhutougg

继续阅读此作者的更多文章