2011-12-07 37 views
3

我正在尝试使用URL连接库编写一个连接到Twitter搜索URL(它返回一个JSON推文列表)的小型java程序。通过代理连接到Java中的URL

我这是从Java教程所采取的代码如下所示:

 public static void main(String[] args) throws Exception { 
     URL oracle = new URL("http://search.twitter.com/search.json?q=hi"); 
     URLConnection yc = oracle.openConnection(); 
     BufferedReader in = new BufferedReader(
           new InputStreamReader(
           yc.getInputStream())); 
     String inputLine; 

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

,但由于某种原因,我不断收到以下异常:

in thread "main" java.net.ConnectException: Connection refused 
    at java.net.PlainSocketImpl.socketConnect(Native Method) 

我不知道这是什么由于我写代码的方式,eclipse设置或者与我的网络有关的东西。我的代理服务器配置了Internet访问。据我所知这是正确配置,因为我得到更新,并可以通过eclipse安装新软件。我是否需要将代理信息以某种方式放在URL方法中,或者是其他问题。

回答

4

URL依赖于代理系统属性,尝试设置代理这样的:

System.setProperty("http.proxyHost", "yourproxyserver"); 
System.setProperty("http.proxyPort", "portnumber"); 
+0

身份验证呢? – Randnum

+0

所以对我来说这将是System.setProperty(“http.proxy.mycompany.com”,“我的公司”); – Randnum

+0

和System.setProperty(“http.8080”,“8080”);? – Randnum

4

不幸的是,在Eclipse中正确的代理设置似乎并没有帮助代理Java程序在Eclipse中开始。同样,将Java系统设置设置为使用全系统代理设置也不会。不管什么时候你有一个需要认证的代理。

正如托马斯·约翰·Eggum说,如果你有那么一个“正常的”非认证代理通过-D设置两个JVM变量http.proxyHosthttp.proxyPort无论是在命令行或编程(见下文)将处理后事。

对于验证代理服务器,即想要查看用户标识和密码的服务器,很多人推荐设置http.proxyUserhttp.proxyPassword。这是不好的建议,因为这些都不起作用。显然它们是在Java文档中定义的而不是

不幸的是,它看起来像“做”身份验证的方式是使用身份验证器,以编程方式。如果你打算这么做,那么你也可以通过编程来完成整个事情,例如包括主机和端口。下面是我如何工作:

public static void main(String[] args) { 
     try { 

     System.setProperty("http.proxyHost", "my.proxy.host"); 
     System.setProperty("http.proxyPort", "8080-or-whatever-proxy-port"); 
     Authenticator.setDefault(new DummyAuthenticator()); 

     /* do your main program stuff */    

     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
    } 

    private static class DummyAuthenticator extends Authenticator { 
     public PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication(
       "my-user-id", "my-password".toCharArray() 
       ); 
     } 
    } 
+0

这有效,更详细,包括用户名/密码认证。 – sversch