Java语言代码示例

  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.hahado.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. }

嵌入代码使用,即可实现使用隧道来进行

猜你喜欢

转载自blog.csdn.net/weixin_73725158/article/details/132202130