2012-10-25 98 views
0

我想通过java从openweathermap.org获取一些数据,但是当我运行代码时,我得到一个ConnectionException。为什么我的连接被拒绝?

我的代码是:

public static void openweathermapTest1() { 
    String uri = "http://openweathermap.org/data/2.1/find/station?lat=55&lon=37&cnt=10"; 
    ClientConfig config = new DefaultClientConfig(); 
    Client client = Client.create(config); 
    WebResource service = client.resource(uri); 
    String xml = service.accept(MediaType.TEXT_XML).get(String.class); 
    System.out.println("Output as XML: " + xml); 
} 

和例外:

Exception in thread "main" 
com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused: connect 
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:151) 
at com.sun.jersey.api.client.Client.handle(Client.java:648)  
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:680) 
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74) 
at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:507) 
at GetPoint.openweathermapTest1(GetPoint.java:110) 
at GetPoint.main(GetPoint.java:142) 

奇怪的是,当我在我的web浏览器中调用this link,我得到预期的数据。怎么可能?我在这里错过了什么?我该如何解决它? (我尝试了所有三个uri,都在Firefox中工作,而不是在我的程序中)

+0

你有没有检查是否有防火墙? – ADTC

+2

我编译你的代码,它工作正常(呃,实际上它提取JSON而不是XML,但它只是当给定一个'text/xml'或'application/xml'' Accept'头时该服务是如何工作的)。问题在于别处。你有没有防火墙运行? – toniedzwiedz

+1

谢谢汤姆。我不明白的是,为什么我可以用firefox连接而不用java连接。他们使用不同的端口吗?我明天会检查我的系统管理员,因为我确实可以控制防火墙。 – Burkhard

回答

1

答案很简单:我的工作计算机在代理之后,只有firefox在使用它。有了一点代理魔法,我终于能够得到预期的结果。

感谢汤姆和吉姆加里森对他们的有用评论!

编辑:我用下面的代码使用代理:

private static void useProxy(String host, int port) 
{ 
    System.setProperty("http.proxySet", "true"); 
    System.setProperty("http.proxyHost", host); 
    System.setProperty("http.proxyPort", String.valueOf(port)); 
} 
-1

我面临同样的问题。当我重新检查我的JAVA安装时,我的问题得到了解决。我有JDK 6和7 ..这种搞砸..所以我完全删除jdk 7,并指向jdk 6.所以命令行版本,eclipse和服务器都应该指向相同的jdk ..这解决了错误。