Android HttpURlConnection未连接

Android HttpURlConnection未连接,android,httpurlconnection,Android,Httpurlconnection,我正在与一个Usgs API建立HttpUrl连接。这是我的网址: “” 经过彻底调试后,似乎connection.connect连接失败,jsonResponse为空 public static String makeHttprequest(URL url) throws IOException { String jsonResponse = ""; HttpURLConnection connection = null; InputStrea

我正在与一个Usgs API建立HttpUrl连接。这是我的网址:

“”

经过彻底调试后,似乎connection.connect连接失败,jsonResponse为空

 public static String makeHttprequest(URL url) throws IOException {
        String jsonResponse = "";
        HttpURLConnection connection = null;
        InputStream stream = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(1000000);
            connection.setConnectTimeout(1500000);

            connection.connect();

            stream = connection.getInputStream();
            jsonResponse = readfromstream(stream);

        } catch (IOException e) {
            Log.e("IOException", "Error while making request");
        }

        return jsonResponse;
    }

刚刚在真实设备上试用了我的应用程序,一切正常。emulator可能出现问题。

一切正常。在我看来,您运行的设备中没有internet连接。您可能正在未连接到internet的计算机中使用emulator

请尝试在真实设备中运行。它对我来说非常好用

有一点建议,请尝试使用改型或OkHttp等库。它们比这些旧方法简单得多

如果坚持使用HttpURLConnection,请尝试以下操作

URL url = new URL(yourUrlString);
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }
或者要更正式地使用HttpURLConnection,请访问此处。它展示了HttpURLConnection API的几种正确用法


使用网络改造。不要使用HttpURLConnection,因为您更容易出错。错误表明您在解析JSON时遇到问题。也许JSON的格式不正确。你能从地震加载器中发布更多相关的代码吗?此外,url应该是,因为HttpUrlConnection提供空输出,所以它给出了有关jason解析的错误。无论如何,代码没有问题,但emulator没有拾取internet连接。