在Java和Python中實現代理IP的方法有所不同
在Java中,您可以使用java.net.Proxy
類來創建一個代理服務器。以下是一個簡單的示例:
import java.net.*;
public class ProxyDemo {
public static void main(String[] args) {
// 創建一個IP地址和端口號的URI對象
URI proxyUri = new URI("http://proxy.example.com:8080");
// 創建一個代理對象
Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyUri);
// 創建一個URL對象
URL url = new URL("http://example.com");
// 使用代理對象打開連接
try (URLConnection connection = url.openConnection(proxy)) {
// 設置請求屬性(可選)
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// 讀取響應內容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
// 輸出響應內容
System.out.println(content.toString());
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
}
在Python中,您可以使用requests
庫來發送帶有代理的HTTP請求。首先,您需要安裝requests
庫(如果尚未安裝):
pip install requests
然后,您可以使用以下代碼創建一個帶有代理的HTTP請求:
import requests
url = "http://example.com"
proxy = "http://proxy.example.com:8080"
response = requests.get(url, proxies={"http": proxy, "https": proxy})
print(response.text)
請注意,這些示例僅用于演示如何在Java和Python中使用代理IP。在實際應用中,您可能需要根據您的需求對這些代碼進行調整。