帮助文档>代理IP>代码示例 > 代码示例-Java

代码示例-Java

发布时间:2021-08-03 21:04

Java HttpURLConnection

  1. package com.qgproxy;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.InputStream;
  4. import java.net.Authenticator;
  5. import java.net.HttpURLConnection;
  6. import java.net.InetSocketAddress;
  7. import java.net.PasswordAuthentication;
  8. import java.net.Proxy;
  9. import java.net.URL;
  10. class QGProxyAuthenticator extends Authenticator {
  11. private String user, password;
  12. public QGProxyAuthenticator(String user, String password) {
  13. this.user = user;
  14. this.password = password;
  15. }
  16. protected PasswordAuthentication getPasswordAuthentication() {
  17. return new PasswordAuthentication(user, password.toCharArray());
  18. }
  19. }
  20. class QGProxy {
  21. public static void main(String args[]) {
  22. // 如果您的本地jdk版本在Java 8 Update 111以上,需要增加以下代码
  23. // System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "false");
  24. // System.setProperty("jdk.http.auth.proxying.disabledSchemes", "false");
  25. String targetUrl = "https://ip.cn/api/index?ip=&type=0";
  26. String proxyIp = "您的代理IP";
  27. int proxyPort = 端口号;
  28. String authKey = "请改成您的Key";
  29. String password = "请改成您的AuthPwd";
  30. try {
  31. URL url = new URL(targetUrl);
  32. Authenticator.setDefault(new QGProxyAuthenticator(authKey, password));
  33. InetSocketAddress socketAddress = new InetSocketAddress(proxyIp, proxyPort);
  34. Proxy proxy = new Proxy(Proxy.Type.HTTP, socketAddress);
  35. HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
  36. byte[] response = readStream(connection.getInputStream());
  37. System.out.println(new String(response));
  38. } catch (Exception e) {
  39. System.out.println(e.getLocalizedMessage());
  40. }
  41. }
  42. public static byte[] readStream(InputStream inStream) throws Exception {
  43. ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  44. byte[] buffer = new byte[1024];
  45. int len = -1;
  46. while ((len = inStream.read(buffer)) != -1) {
  47. outSteam.write(buffer, 0, len);
  48. }
  49. outSteam.close();
  50. inStream.close();
  51. return outSteam.toByteArray();
  52. }
  53. }

Java okhttp

  1. package com.qgproxy;
  2. import okhttp3.*;
  3. import java.io.IOException;
  4. import java.net.InetSocketAddress;
  5. import java.net.Proxy;
  6. import java.util.concurrent.TimeUnit;
  7. public class QGProxy {
  8. final static String proxyIp = "您的代理IP";
  9. final static Integer proxyPort = 端口号;
  10. final static String authKey = "请改成您的Key";
  11. final static String password = "请改成您的AuthPwd";
  12. public Response request() throws IOException {
  13. Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
  14. OkHttpClient client = new OkHttpClient.Builder()
  15. .proxy(proxy)
  16. .proxyAuthenticator((route, response) -> {
  17. String credential = Credentials.basic(authKey, password);
  18. return response.request().newBuilder().header("Proxy-Authorization", credential).build();
  19. }).
  20. build();
  21. Request request = new Request.Builder().url("https://ip.cn/api/index?type=0").get().build();
  22. return client.newCall(request).execute();
  23. }
  24. public static void main(String[] args) {
  25. QGProxy qgProxy = new QGProxy();
  26. try {
  27. Response resp = qgProxy.request();
  28. System.out.println(resp.body().string());
  29. } catch (Exception e) {
  30. System.out.printf("failed to proxy: %s\n", e.getMessage());
  31. }
  32. }
  33. }

Java jsonp

  1. package com.qgproxy;
  2. import org.jsoup.Jsoup;
  3. import org.jsoup.nodes.Document;
  4. import java.io.IOException;
  5. import java.net.Authenticator;
  6. import java.net.InetSocketAddress;
  7. import java.net.PasswordAuthentication;
  8. import java.net.Proxy;
  9. public class QGProxy {
  10. final static String proxyIp = "您的代理IP";
  11. final static Integer proxyPort = 端口号;
  12. final static String authKey = "请改成您的Key";
  13. final static String password = "请改成您的AuthPwd";
  14. public static void main(String[] args) throws Exception {
  15. String targetUrl = "https://ip.cn/api/index?ip=&type=0";
  16. Authenticator.setDefault(new Authenticator() {
  17. public PasswordAuthentication getPasswordAuthentication() {
  18. return new PasswordAuthentication(authKey, password.toCharArray());
  19. }
  20. });
  21. Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
  22. try {
  23. Document doc = Jsoup.connect(url).timeout(10000).proxy(proxy).get();
  24. if (doc != null) {
  25. System.out.println(doc.body().html());
  26. }
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }

Java HttpClient 3.X

  1. package com.qgproxy;
  2. import java.io.IOException;
  3. import org.apache.http.HttpHost;
  4. import org.apache.http.auth.AuthScope;
  5. import org.apache.http.auth.UsernamePasswordCredentials;
  6. import org.apache.http.client.CredentialsProvider;
  7. import org.apache.http.client.config.RequestConfig;
  8. import org.apache.http.client.methods.CloseableHttpResponse;
  9. import org.apache.http.client.methods.HttpGet;
  10. import org.apache.http.impl.client.BasicCredentialsProvider;
  11. import org.apache.http.impl.client.CloseableHttpClient;
  12. import org.apache.http.impl.client.HttpClients;
  13. public class QGProxy {
  14. public static void main(String[] args) {
  15. String targetUrl = "ip.cn/api/index?ip=&type=0"; // 访问的目标站点
  16. String proxyIp = "您的代理IP";
  17. int proxyPort = 端口号;
  18. String authKey = "请改成您的Key";
  19. String password = "请改成您的AuthPwd";
  20. try {
  21. HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http");
  22. HttpHost target = new HttpHost(targetUrl, 80);
  23. // 设置认证
  24. CredentialsProvider provider = new BasicCredentialsProvider();
  25. provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(authKey, password));
  26. CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
  27. RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
  28. HttpGet httpGet = new HttpGet("/ip");
  29. httpGet.setConfig(config);
  30. CloseableHttpResponse resp = null;
  31. resp = httpClient.execute(target, httpGet);
  32. if (resp.getStatusLine().getStatusCode() == 200) {
  33. System.out.println("OK");
  34. }
  35. System.out.println(resp.getStatusLine());
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }

Java HttpClient 4.X

  1. package com.qgproxy
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.io.IOException;
  5. import java.net.URI;
  6. import java.util.Arrays;
  7. import java.util.ArrayList;
  8. import java.util.HashSet;
  9. import java.util.List;
  10. import java.util.Set;
  11. import org.apache.http.Header;
  12. import org.apache.http.HeaderElement;
  13. import org.apache.http.HttpHost;
  14. import org.apache.http.auth.AuthScope;
  15. import org.apache.http.auth.UsernamePasswordCredentials;
  16. import org.apache.http.client.AuthCache;
  17. import org.apache.http.client.CredentialsProvider;
  18. import org.apache.http.client.HttpRequestRetryHandler;
  19. import org.apache.http.client.config.RequestConfig;
  20. import org.apache.http.client.config.AuthSchemes;
  21. import org.apache.http.client.entity.GzipDecompressingEntity;
  22. import org.apache.http.client.entity.UrlEncodedFormEntity;
  23. import org.apache.http.client.methods.CloseableHttpResponse;
  24. import org.apache.http.client.methods.HttpGet;
  25. import org.apache.http.client.methods.HttpPost;
  26. import org.apache.http.client.methods.HttpRequestBase;
  27. import org.apache.http.client.protocol.HttpClientContext;
  28. import org.apache.http.config.Registry;
  29. import org.apache.http.config.RegistryBuilder;
  30. import org.apache.http.conn.socket.ConnectionSocketFactory;
  31. import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
  32. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  33. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  34. import org.apache.http.impl.auth.BasicScheme;
  35. import org.apache.http.impl.client.BasicAuthCache;
  36. import org.apache.http.impl.client.BasicCredentialsProvider;
  37. import org.apache.http.impl.client.CloseableHttpClient;
  38. import org.apache.http.impl.client.HttpClients;
  39. import org.apache.http.impl.client.ProxyAuthenticationStrategy;
  40. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  41. import org.apache.http.message.BasicHeader;
  42. import org.apache.http.message.BasicNameValuePair;
  43. import org.apache.http.NameValuePair;
  44. import org.apache.http.util.EntityUtils;
  45. public class QGProxy {
  46. final static String proxyHost = "您的代理IP";
  47. final static Integer proxyPort = 端口号;
  48. final static String proxyUser = "请改成您的key";
  49. final static String proxyPass = "请改成您的password";
  50. private static PoolingHttpClientConnectionManager cm = null;
  51. private static HttpRequestRetryHandler httpRequestRetryHandler = null;
  52. private static HttpHost proxy = null;
  53. private static CredentialsProvider credsProvider = null;
  54. private static RequestConfig reqConfig = null;
  55. static {
  56. ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
  57. LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
  58. Registry registry = RegistryBuilder.create()
  59. .register("http", plainsf)
  60. .register("https", sslsf)
  61. .build();
  62. cm = new PoolingHttpClientConnectionManager(registry);
  63. cm.setMaxTotal(10);
  64. cm.setDefaultMaxPerRoute(5);
  65. proxy = new HttpHost(proxyHost, proxyPort, "http");
  66. credsProvider = new BasicCredentialsProvider();
  67. credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPass));
  68. reqConfig = RequestConfig.custom()
  69. .setExpectContinueEnabled(false)
  70. .setProxy(new HttpHost(proxyHost, proxyPort))
  71. .build();
  72. }
  73. public static void doRequest(HttpRequestBase httpReq) {
  74. CloseableHttpResponse httpResp = null;
  75. try {
  76. httpReq.setConfig(reqConfig);
  77. CloseableHttpClient httpClient = HttpClients.custom()
  78. .setConnectionManager(cm)
  79. .setDefaultCredentialsProvider(credsProvider)
  80. .build();
  81. AuthCache authCache = new BasicAuthCache();
  82. authCache.put(proxy, new BasicScheme());
  83. authCache.put(proxy, new BasicScheme(ChallengeState.PROXY));
  84. HttpClientContext localContext = HttpClientContext.create();
  85. localContext.setAuthCache(authCache);
  86. httpResp = httpClient.execute(httpReq, localContext);
  87. System.out.println(httpResp.getStatusLine().getStatusCode(););
  88. BufferedReader rd = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
  89. String line = "";
  90. while((line = rd.readLine()) != null) {
  91. System.out.println(line);
  92. }
  93. } catch (Exception e) {
  94. e.printStackTrace();
  95. } finally {
  96. try {
  97. if (httpResp != null) {
  98. httpResp.close();
  99. }
  100. } catch (IOException e) {
  101. e.printStackTrace();
  102. }
  103. }
  104. }
  105. public static void main(String[] args) {
  106. String targetUrl = "https://ip.cn/api/index?ip=&type=0";
  107. try {
  108. HttpGet httpGet = new HttpGet(targetUrl);
  109. doRequest(httpGet);
  110. } catch (Exception e) {
  111. e.printStackTrace();
  112. }
  113. }
  114. }
本文导读

客户热线: