JAVA設置代理訪問網絡方式
點關注不迷路,歡迎再訪!
一.背景介紹
實際工作中有些的網絡不能直接連接到外網, 需要使用http或是https或是socket代理來連接到外網, 這裏是java使用代理連接到外網的一些方法.
二.實現用java.net.Proxy類
HttpInvokerProxyFactoryBean httpInvokerProxyFactoryBean = new HttpInvokerProxyFactoryBean();
httpInvokerProxyFactoryBean.setServiceInterface(ITpaicCacheManager.class);
httpInvokerProxyFactoryBean.setServiceUrl(address);
HttpClient httpClient = new HttpClient();
HttpClientParams clientParam = new HttpClientParams();
clientParam.setConnectionManagerTimeout(3000);
clientParam.setSoTimeout(20000);
clientParam.setConnectionManagerClass(MultiThreadedHttpConnectionManager.class);
httpClient.setParams(clientParam);
httpInvokerProxyFactoryBean.setHttpInvokerRequestExecutor(new CommonsHttpInvokerRequestExecutor(httpClient));
try {
httpInvokerProxyFactoryBean.afterPropertiesSet();
ITpaicCacheManager cacheManagerRemote = (ITpaicCacheManager)httpInvokerProxyFactoryBean.getObject();
return cacheManagerRemote;
} catch (Throwable e) {
cacheClientInfo.setError();
cacheClientInfo.setClientInfo(address + "連接失敗" + e.getMessage());
return null;
}
三.直接設置系統屬性,設置後所有網絡請求都有效
只有在所以網絡請求都需要代理時纔可以使用系統屬性
System.setProperty("proxyType", "4");
System.setProperty("proxyPort", "xxxx"));
System.setProperty("proxyHost", "x.x.x.x");
System.setProperty("proxySet", "true");