【问题标题】:Connection time out while reading JSON from URL从 URL 读取 JSON 时连接超时
【发布时间】: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);
      });

当我昨天尝试时,这实际上工作正常,但现在不知何故导致异常。 非常感谢您对此的任何帮助。

【问题讨论】:

    标签: java json getjson


    【解决方案1】:

    我的防病毒软件阻止了访问。我已禁用它,现在没有发现任何问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2011-12-05
      • 2014-12-07
      • 2021-12-08
      • 2022-08-24
      • 2019-02-01
      • 2017-09-28
      相关资源
      最近更新 更多