HttpURL连接错误

HttpURLConnection error

我想从网站获取 HTML,为此我使用了 this 代码。 当我尝试添加 this code from the documentation I get this error:

            //Get HTML
            URL url = new URL("http://www.android.com/");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                readStream(in);
                finally {
                    urlConnection.disconnect();
                }
            }

出了什么问题?我是不是忘了导入一些东西?

您缺少 catch 子句。将其放在 finally 子句之前:

} catch (Exception e) { //it's bad practice to catch Exception, specify it more if you can, i just don't know what errors InputStream throws
    Log.e("ClassTag", e.getMessage(), e);
} finally { /* ... */ }

finally块没有进入try块,改成:

 try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
 }
 finally {
    urlConnection.disconnect();
}

还要确保您已导入 java.net.URL

您没有忘记导入任何东西。

代码有几处错误。

1) 您缺少与 try 一起使用的 catch 块,并且您的 finally 语句错误地位于 if 中。它应该如下所示:

try {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
} catch (Exception e) { // best practice is to be more specific with the Exception type
    urlConnection.disconnect();
    Log.w("Login", "Error downloading HTML from " + url);        
} finally {
    if(urlConnection != null) {
                urlConnection.disconnect();
    }
}

2) 在您在文档中关注的那个示例中,他们让您决定如何处理从 urlConnection.

检索到的流。

因此,在您的 activity 中创建您自己的 void readStream(InputStream in) 方法,然后可以使用 InputStream。写入磁盘,显示在屏幕上,由您决定。