Java接入示例
发布时间: 2023-07-20 15:33:14
阅读量: 463 人次
隧道代理服务器地址
版本 | 代理服务器地址 | 端口 |
---|---|---|
隧道代理(1分钟版) | one-tun.sshttp.cn | 3200 |
隧道代理(每次请求换IP版) | dyn-tun.sshttp.cn | 3100 |
示例说明
实例id和实例密码(后台隧道代理产品页面可查看):
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
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.client.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
public class HttpClientDemo {
// 代理隧道验证信息
private final static String ProxyUser = "实例id(后台-我的产品-隧道代理页面可查)";
private final static String ProxyPass = "实例密码(后台-我的产品-隧道代理页面可查)";
// 代理服务器
private final static String ProxyHost = "dyn-tun.sshttp.cn";
private final static Integer ProxyPort = 3100;
private static HttpHost proxy = null;
private static HttpClientBuilder clientBuilder = null;
static {
proxy = new HttpHost(ProxyHost, ProxyPort, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(ProxyUser, ProxyPass));
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(3000).build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(3000)
.setConnectTimeout(3000)
.setSocketTimeout(3000)
.setExpectContinueEnabled(false)
.setProxy(proxy)
.build();
clientBuilder = HttpClients.custom()
.setDefaultSocketConfig(socketConfig)
.disableAutomaticRetries()
.setDefaultRequestConfig(requestConfig)
.setDefaultCredentialsProvider(credsProvider);
}
private static void getUrlContent(String url) {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse httpResp = null;
try {
// JDK 8u111版本后,目标页面为HTTPS协议,启用proxy用户密码鉴权
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
AuthCache authCache = new BasicAuthCache();
authCache.put(proxy, new BasicScheme());
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
httpResp = clientBuilder.build().execute(httpGet, localContext);
String html = IOUtils.toString(httpResp.getEntity().getContent(), "GB2312");
System.out.println(html);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (httpResp != null) {
httpResp.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
// 要访问的目标页面
String targetUrl = "http://httpbin.org/ip";
getUrlContent(targetUrl);
}
}