如何在java中使用HTTP代理 [英] How to use an HTTP proxy in java

查看:323
本文介绍了如何在java中使用HTTP代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个连接到网站并检查一些代码的代码,比如爬虫。但我需要通过代理连接并更改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 建议,您可以使用一些第三方库来更好地满足您的需求。

Or as lisak suggested, you can use some 3rd party libraries which supports your need better.

这篇关于如何在java中使用HTTP代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆