我想从一个网站获取HTML,因为我使用的是这代码。当我尝试从文档中添加这代码时,我得到了这一错误
//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();
}
}哪里出了问题?我忘了进口一些东西了吗?
发布于 2015-10-07 13:25:29
你没有忘记进口任何东西。
密码有几处问题。
1)您丢失了catch块以配合try,并且您的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中检索到,它们将由您来决定如何处理它。
因此,在您的活动中创建您自己的void readStream(InputStream in)方法,然后可以使用InputStream。把它写到磁盘上,显示在屏幕上,由你来决定。
发布于 2015-10-07 13:22:56
您缺少了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 { /* ... */ }发布于 2015-10-07 13:23:14
finally块不进入try块,将其更改为:
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}
finally {
urlConnection.disconnect();
}还要确保您已经导入了java.net.URL。
https://stackoverflow.com/questions/32993284
复制相似问题