使用java中的代理代码连接到站点

时间:2010-06-14 08:55:53

标签: java proxy connection

我想通过java中的代理连接到网站。这是我写的代码:

public class ConnectThroughProxy 
{
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy ip", 8080));
    public static void main(String[] args) 
    {
        try
        {
            URL url = new URL("http://www.rgagnon.com/javadetails/java-0085.html");
            URLConnection connection=url.openConnection();
            String encoded = new String(Base64.encode(new String("user_name:pass_word").getBytes()));
            connection.setDoOutput(true);
            connection.setRequestProperty("Proxy-Authorization","Basic "+encoded);
            String page="";
            String line;
            StringBuffer tmp = new StringBuffer();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line=in.readLine()) != null)
            {
                page.concat(line + "\n");
            }
            System.out.println(page);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

尝试运行此代码时会抛出以下错误:

  

java.lang.IllegalArgumentException:消息头值中的非法字符:Basic dXNlcl9uYW1lOnBhc3Nfd29yZA ==
  在sun.net.www.protocol.http.HttpURLConnection.checkMessageHeader(HttpURLConnection.java:323)
  在sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:2054)
  在test.ConnectThroughProxy.main(ConnectThroughProxy.java:30)

任何想法怎么做?

3 个答案:

答案 0 :(得分:11)

如果您只是尝试通过HTTP代理服务器发出HTTP请求,则不需要付出太多努力。这里有一篇文章:http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html

但它基本上归结为只在命令行或代码中设置http.proxyHost和http.proxyPort环境属性:

// Set the http proxy to webcache.mydomain.com:8080
System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setProperty("http.proxyPort", "8080");

// Next connection will be through proxy.
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();

// Now, let's 'unset' the proxy.
System.clearProperty("http.proxyHost");

// From now on HTTP connections will be done directly.

答案 1 :(得分:4)

在我看来,你根本就没有使用你的Proxy实例。我认为你应该在创建 URLConnection 实例时传递它:

URLConnection connection=url.openConnection(proxy);

设置环境属性 http.proxy 更容易,当使用某些第三方库而没有代理实例传递仅支持可能的解决方案时,但它的缺点是它是为整个过程全局设置的。 / p>

答案 2 :(得分:2)

我使用的是谷歌数据API,我获得代理设置的唯一方法是提供与代理相关的所有参数,甚至认为它们被设置为空:

/usr/java/jdk1.7.0_04/bin/java -Dhttp.proxyHost=10.128.128.13 
    -Dhttp.proxyPassword -Dhttp.proxyPort=80 -Dhttp.proxyUserName 
    -Dhttps.proxyHost=10.128.128.13 -Dhttps.proxyPassword -Dhttps.proxyPort=80 
    -Dhttps.proxyUserName com.stackoverflow.Runner

其中,不需要用户名和密码,并且相同的http和https服务器设置为相同,以及端口号(如果这也是您的情况)。请注意,同样的HTTP代理也作为HTTPS服务器提供,以及其端口号(来自https://code.google.com/p/syncnotes2google/issues/detail?id=2#c16的引用)。

如果您的Java类有一个类“URL”的实例,它应该选择那些配置......