【发布时间】:2016-07-09 15:06:14
【问题描述】:
我正在运行下面的程序以从 URL 获取 JSON 字符串。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class Temp {
public static void main(String args[]) throws Exception {
System.out.println(readUrl("http://ip-api.com/json/31.15.112.160"));
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
}
它的结果是
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
但是,如果我尝试直接从浏览器访问 URL,它不会引发任何问题。
下面的 jQuery 调用也可以正常工作。
$.getJSON("http://ip-api.com/json/31.15.112.160",
function(data){
document.getElementById("jsonIpDataISP").value = data.isp;
document.getElementById("jsonIpDataCity").value = data.city;
document.getElementById("jsonIpDataCountry").value = data.country;
document.getElementById("jsonIpDataOrg").value = data.org;
document.getElementById("jsonIpDataTimeZone").value = data.timezone;
alert(data.isp);
alert(data.city);
alert(data.country);
alert(data.org);
alert(data.timezone);
});
当我昨天尝试时,这实际上工作正常,但现在不知何故导致异常。 非常感谢您对此的任何帮助。
【问题讨论】: