背景
经常会遇到服务器端限制访问速度,常见的是限制IP,这时候我们就需要设置代理IP来解除这种限制。
设置代理IP(多种实现方式)
设置系统属性方式
发送HTTP请求前通过设置JVM中的系统属性来实现
1 2 3 4 5
| // HTTP/HTTPS Proxy System.setProperty("http.proxyHost", yourProxyIp); System.setProperty("http.proxyPort", yourProxyProt); System.setProperty("https.proxyHost", yourProxyIp); System.setProperty("https.proxyPort", yourProxyProt);
|
使用HttpClient时设置代理
直接引用HttpClient官方的示例代码进行说明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils;
/** * How to send a request via proxy. * * @since 4.0 */ public class ClientExecuteProxy {
public static void main(String[] args)throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpHost target = new HttpHost("httpbin.org", 443, "https"); HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
RequestConfig config = RequestConfig.custom() .setProxy(proxy) .build(); HttpGet request = new HttpGet("/"); request.setConfig(config);
System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);
CloseableHttpResponse response = httpclient.execute(target, request); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); } finally { response.close(); } } finally { httpclient.close(); } }
}
|