HttpURlConnection无法连接

时间:2019-02-07 08:37:14

标签: android httpurlconnection

我正在使用Usgs API进行HttpUrlConnection。这是我的网址:

https://earthquake.usgs.gov/fdsnws/event/1/queryformat=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10

经过彻底调试后,似乎在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;
    }

This is Log

2 个答案:

答案 0 :(得分:1)

一切看起来不错。在我看来,您正在运行的设备中没有互联网连接。可能您正在未连接到互联网的计算机中使用模拟器。

请尝试在真实设备中运行。对我来说很完美。

一些建议,请尝试使用Retrofit或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的几种正确用法。

https://developer.android.com/reference/java/net/HttpURLConnection

答案 1 :(得分:0)

只是在真实设备上尝试了我的应用,一切都按预期运行,所以模拟器可能有问题。