httpclient设置proxy与proxyselector


  1. If single proxy for all targets is enough for you:

    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory( HttpClientBuilder.create() .setProxy(new HttpHost("myproxy.com", 80, "http")) .build()); restTemplate = new RestTemplate(clientHttpRequestFactory);
  2. Or if you want to use different proxies for different target URIs, schemas, etc. you can useHttpRoutePlanner with custom ProxySelector:

    HttpRoutePlanner routePlanner = new SystemDefaultRoutePlanner(new MyProxySelector()); HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory( HttpClientBuilder.create() .setRoutePlanner(routePlanner) .build()); restTemplate = new RestTemplate(clientHttpRequestFactory);
  3. Example proxy selector: MyProxySelector.java:
  4. package hello; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Proxy.Type; import java.net.ProxySelector; import java.net.SocketAddress; import java.net.URI; import java.util.ArrayList; import java.util.List; public class MyProxySelector extends ProxySelector { ProxySelector defaultproxySelector = ProxySelector.getDefault(); ArrayList<Proxy> noProxy = new ArrayList<Proxy>(); ArrayList<Proxy> secureProxy = new ArrayList<Proxy>(); ArrayList<Proxy> sociaMediaProxy = new ArrayList<Proxy>(); public MyProxySelector(){ noProxy.add(Proxy.NO_PROXY); secureProxy.add(new Proxy(Type.HTTP, new InetSocketAddress( "secure.proxy.mycompany.com", 8080))); sociaMediaProxy.add(new Proxy(Type.HTTP, new InetSocketAddress( "social-media.proxy.mycompany.com", 8080))); } @Override public List<Proxy> select(URI uri) { // No proxy for local company addresses. if ( uri.getHost().toLowerCase().endsWith("mycompany.com") ) { return noProxy ; } // Special proxy for social networks. String host = uri.getHost().toLowerCase(); if ( host.endsWith("facebook.com") || host.endsWith("twitter.com") || host.endsWith("cfapps.io") || host.endsWith("flickr.com") ) { return sociaMediaProxy ; } // for https URIs use secureProxy if ( uri.getScheme().toLowerCase().equals("https") ){ return secureProxy ; } if (defaultproxySelector != null) { return defaultproxySelector.select(uri); } return noProxy; } @Override public void connectFailed(URI arg0, SocketAddress arg1, IOException arg2) { // TODO Auto-generated method stub } }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM