gpt4 book ai didi

java - 如何将 java.net.URL/URLConnection 与代理链一起使用

转载 作者:行者123 更新时间:2023-12-03 23:08:25 25 4
gpt4 key购买 nike

我尝试使用 java 通过代理链(不止一个)加载网站。每个请求都应该能够使用另一个链。这是我第一次快速而肮脏的尝试:

// My proxies and there ports marked with pIP1 pPort1, pIP2 pPort2...
Socket socket = new Socket(pIP1, pPort1);
OutputStream out = socket.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String connectOverProxy1ToProxy2 = "CONNECT " + pIP2 + ":" + pPort2 + " HTTP/1.1\n\n";
String connectHost = "GET http://stackoverflow.com/ HTTP/1.1\n\n";

out.write((connectOverProxy1ToProxy2 + connectHost).getBytes());
out.flush();

String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);

out.close();
in.close();

作为回应,我收到了这个:

HTTP/1.0 200 Connection established
Proxy-agent: tinyproxy/1.8.3

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Cache-Control: public, max-age=30
Expires: Mon, 08 Apr 2013 11:42:08 GMT
X-Frame-Options: SAMEORIGIN
Date: Mon, 08 Apr 2013 11:41:36 GMT
Last-Modified: Mon, 08 Apr 2013 11:41:08 GMT
Vary: *
Content-Length: 182825

<!DOCTYPE html>
<html>
[..]
</html>

让我们来解决问题。现在我尝试使用 URL/URLConnection 加载页面以使用 java 包的完整处理和功能。有没有一种方法可以将 URL/URLConnection 与代理链而不是单个代理一起使用?

感谢您的帮助...

最佳答案

HttpUrlConnection 类通过使用 proxy-related system settings 支持代理。 .

但是,您可以通过调用 ProxySelector.setDefault() 来更改默认的代理选择机制。并提供您自己的 ProxySelector 子类。

通过覆盖 select(URL)方法,您可以返回该 URL 所需的代理。我会首先尝试仅返回链中的“第一个”代理,然后查看 HttpUrlConnection 是否自动通过代理链。

关于java - 如何将 java.net.URL/URLConnection 与代理链一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15878720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com