如何通过代理IP访问目标网站(Java)
发布时间: 2022-05-31 10:23:08
阅读量: 1130 人次
相关API
代码中所涉及的API可在【API接入指南】中查看。
参考代码
public class Main {
// 实例ID(后台可查)
private static String appKey = "appKey";
// 实例密码(后台可查)
private static String appSecret = "appSecret";
// API接口(API接入指南可查)
private static String api = "https://api.sshttp.com/getIp?appKey=%s&appSecret=%s&cnt=1&wt=text";
private static int timeout = 10000;
private static HttpClientBuilder clientBuilder = null;
// 获取代理IP
private static HttpHost getProxy() throws IOException {
CloseableHttpResponse httpResp = null;
try {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(timeout)
.setConnectTimeout(timeout)
.setSocketTimeout(timeout)
.setExpectContinueEnabled(false)
.setProxy(null)
.build();
HttpClientContext localContext = HttpClientContext.create();
HttpGet httpReq = new HttpGet(String.format(api, appKey, appSecret));
httpResp = clientBuilder
.setDefaultRequestConfig(requestConfig)
.build().execute(httpReq, localContext);
if (httpResp.getStatusLine().getStatusCode() == 200) {
String content = IOUtils.toString(httpResp.getEntity().getContent(), "UTF-8");
System.out.println("API response: " + content);
if (!StringUtils.isEmpty(content)) {
String[] splits = content.split(":");
if (splits.length == 2) {
return new HttpHost(splits[0], Integer.parseInt(splits[1]));
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
httpResp.close();
}
return null;
}
// 访问目标网站
public static void getUrlContent(String url) throws IOException {
CloseableHttpResponse httpResp = null;
try {
// 获取代理IP
HttpHost proxy = getProxy();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(timeout)
.setConnectTimeout(timeout)
.setSocketTimeout(timeout)
.setExpectContinueEnabled(false)
.setProxy(proxy)
.build();
HttpClientContext localContext = HttpClientContext.create();
httpResp = clientBuilder
.setDefaultRequestConfig(requestConfig)
.build().execute(new HttpGet(url), localContext);
String content = IOUtils.toString(httpResp.getEntity().getContent(), "UTF-8");
System.out.println("Target response:" + content);
} catch (IOException e) {
e.printStackTrace();
} finally {
httpResp.close();
}
}
public static void main(String[] args) {
// 要访问的目标页面
String targetUrl = "http://httpbin.org/ip";
for (int i = 0; i < 5; i++) {
getUrlContent(targetUrl);
Thread.sleep(timeout);
}
}
}


黑公网安备 23100002000084号