0
我在程序的下面運行以從URL中獲取JSON字符串。從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);
});
這實際上工作正常,當我昨天嘗試,但不知何故它現在導致異常。 真的很感謝這方面的幫助。