如何在 Java 中使用 HTTP 代理 [英] How to use an HTTP proxy in java
问题描述
我正在编写一个连接到网站并检查一些代码的代码,比如一个爬虫.但是我需要通过代理连接并更改 IP 地址(因此它不会在服务器日志中显示客户端的 IP).
I am writing a code that connects to websites and checks some code, like a crawler. But I need to connect trough a proxy and change the IP address (so it doesn't show the client's IP in the server logs).
这如何通过java来完成?
How can this be done through java?
推荐答案
您可以使用 java 系统属性来设置代理或将其作为命令行选项传递.
You can use the java system properties to set up a proxy or pass it as command line options.
您可以在此处找到一些详细信息和示例.
You can find some details and samples here.
例如:在打开连接之前
System.setProperty("http.proxyHost", "myProxyServer.com");
System.setProperty("http.proxyPort", "80");
或者您可以使用系统中配置的默认网络代理
Or you can use the default network proxies configured in the sytem
System.setProperty("java.net.useSystemProxies", "true");
从 Java 1.5 开始,您可以创建代理实例并将其传递给 openConnection()
方法.
Since Java 1.5 you can create a instance of proxy and pass it to the openConnection()
method.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("123.0.0.1", 8080));
URL url = new URL("http://www.yahoo.com");
HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy);
uc.connect();
或者按照 lisak 的建议,您可以使用一些更好地支持您的需求的第 3 方库.
Or as lisak suggested, you can use some 3rd party libraries which supports your need better.
这篇关于如何在 Java 中使用 HTTP 代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!