分享页面
拖动logo到书签栏,立即收藏易兹代理
首页
短效代理
独享代理
隧道代理
静态代理
开发者
开发者中心
API
强大的API支持,让您轻松集成和定制产品,实现更灵活的应用和创新功能
示例代码
获取丰富的示例代码,加速开发过程,更快集成到你的应用
SDK下载
下载最新的软件开发工具包(SDK),简化开发流程,提高开发效率
联系我们
控制台
|
登录/注册
子
用户在实名认证前无法开通业务
充值
未支付订单
未完成工单
未读消息
会员中心
退出登录
产品介绍
开发者指南
API接口
SDK
SDK
代理IP
SDK下载
C语言代码示例
Go语言代码示例
PHP语言代码示例
Python语言代码示例
Java语言代码示例
Shell语言代码示例
C#语言代码示例
Node语言代码示例
隧道代理 Go 语言接入指南
隧道代理 Java 语言代码示例
隧道代理 Python 语言接入指南
Python自动化测试Selenium+chrome连接代理ip(白名单模式)
Python自动化测试Selenium+chrome连接代理ip(账密模式)
SDK
>
代理IP
>
Java语言代码示例
Java语言代码示例
发布时间:2022-06-21 09:21
## Java HttpURLConnection ```java package com.ezproxy; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.URL; class QGProxyAuthenticator extends Authenticator { private String user, password; public QGProxyAuthenticator(String user, String password) { this.user = user; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password.toCharArray()); } } class QGProxy { public static void main(String args[]) { // 如果您的本地jdk版本在Java 8 Update 111以上,需要增加以下代码 // System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "false"); // System.setProperty("jdk.http.auth.proxying.disabledSchemes", "false"); String targetUrl = "https://test.ipw.cn"; // 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing String proxyIp = "您的代理IP"; int proxyPort = 端口号; String authKey = "请改成您的Key"; String password = "请改成您的AuthPwd"; try { URL url = new URL(targetUrl); Authenticator.setDefault(new QGProxyAuthenticator(authKey, password)); InetSocketAddress socketAddress = new InetSocketAddress(proxyIp, proxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP, socketAddress); HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy); byte[] response = readStream(connection.getInputStream()); System.out.println(new String(response)); } catch (Exception e) { System.out.println(e.getLocalizedMessage()); } } public static byte[] readStream(InputStream inStream) throws Exception { ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray(); } } ``` ## Java okhttp(4.10.0版本以上) ```java package com.ezproxy; import okhttp3.*; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.util.concurrent.TimeUnit; public class QGProxy { final static String proxyIp = "您的代理IP"; final static Integer proxyPort = 端口号; final static String authKey = "请改成您的Key"; final static String password = "请改成您的AuthPwd"; public Response request() throws IOException { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort)); OkHttpClient client = new OkHttpClient.Builder() .proxy(proxy) .proxyAuthenticator((route, response) -> { String credential = Credentials.basic(authKey, password); return response.request().newBuilder().header("Proxy-Authorization", credential).build(); }). build(); Request request = new Request.Builder().url("https://api.ipify.org").get().build(); return client.newCall(request).execute(); } public static void main(String[] args) { QGProxy qgProxy = new QGProxy(); try { Response resp = qgProxy.request(); System.out.println(resp.body().string()); } catch (Exception e) { System.out.printf("failed to proxy: %s\n", e.getMessage()); } } } ``` ## Java jsoup ```java package com.ezproxy; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; import java.net.Authenticator; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; public class QGProxy { final static String proxyIp = "您的代理IP"; final static Integer proxyPort = 端口号; final static String authKey = "请改成您的Key"; final static String password = "请改成您的AuthPwd"; public static void main(String[] args) throws Exception { String targetUrl = "https://test.ipw.cn"; // 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing Authenticator.setDefault(new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(authKey, password.toCharArray()); } }); // 如果您的本地jdk版本在Java 8 Update 111以上,需要增加以下代码 // System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "false"); // System.setProperty("jdk.http.auth.proxying.disabledSchemes", "false"); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort)); try { Document doc = Jsoup.connect(targetUrl).ignoreContentType(true).timeout(10000).proxy(proxy).get(); if (doc != null) { System.out.println(doc.body().html()); } } catch (IOException e) { e.printStackTrace(); } } } ``` ## Java HttpClient 3.X ```java package com.ezproxy; import java.io.IOException; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; 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.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class QGProxy { public static void main(String[] args) { String targetUrl = "https://test.ipw.cn"; // 访问的目标站点 // 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing String proxyIp = "您的代理IP"; int proxyPort = 端口号; String authKey = "请改成您的Key"; String password = "请改成您的AuthPwd"; try { HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http"); HttpHost target = new HttpHost(targetUrl, 80); // 设置认证 CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(authKey, password)); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build(); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpGet httpGet = new HttpGet("/ip"); httpGet.setConfig(config); CloseableHttpResponse resp = null; resp = httpClient.execute(target, httpGet); if (resp.getStatusLine().getStatusCode() == 200) { System.out.println("OK"); } System.out.println(resp.getStatusLine()); } catch (IOException e) { e.printStackTrace(); } } } ``` ## Java HttpClient 4.X ```java package com.ezproxy import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.http.Header; import org.apache.http.HeaderElement; 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.HttpRequestRetryHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.AuthSchemes; import org.apache.http.client.entity.GzipDecompressingEntity; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.LayeredConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 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.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.ProxyAuthenticationStrategy; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.NameValuePair; import org.apache.http.util.EntityUtils; public class QGProxy { final static String proxyHost = "您的代理IP"; final static Integer proxyPort = 端口号; final static String proxyUser = "请改成您的key"; final static String proxyPass = "请改成您的password"; private static PoolingHttpClientConnectionManager cm = null; private static HttpRequestRetryHandler httpRequestRetryHandler = null; private static HttpHost proxy = null; private static CredentialsProvider credsProvider = null; private static RequestConfig reqConfig = null; static { ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory(); Registry registry = RegistryBuilder.create() .register("http", plainsf) .register("https", sslsf) .build(); cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(10); cm.setDefaultMaxPerRoute(5); proxy = new HttpHost(proxyHost, proxyPort, "http"); credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPass)); reqConfig = RequestConfig.custom() .setExpectContinueEnabled(false) .setProxy(new HttpHost(proxyHost, proxyPort)) .build(); } public static void doRequest(HttpRequestBase httpReq) { CloseableHttpResponse httpResp = null; try { httpReq.setConfig(reqConfig); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .setDefaultCredentialsProvider(credsProvider) .build(); AuthCache authCache = new BasicAuthCache(); authCache.put(proxy, new BasicScheme()); authCache.put(proxy, new BasicScheme(ChallengeState.PROXY)); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); httpResp = httpClient.execute(httpReq, localContext); System.out.println(httpResp.getStatusLine().getStatusCode();); BufferedReader rd = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent())); String line = ""; while((line = rd.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (httpResp != null) { httpResp.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { String targetUrl = "https://api.ipify.org"; try { HttpGet httpGet = new HttpGet(targetUrl); doRequest(httpGet); } catch (Exception e) { e.printStackTrace(); } } } ```
本文导读