【发布时间】:2010-05-18 20:57:34
【问题描述】:
打开与网站的连接并随后阅读该页面上的信息的首选方式是什么?似乎有很多关于不同部分的具体问题,但没有明确和简单的例子。
【问题讨论】:
打开与网站的连接并随后阅读该页面上的信息的首选方式是什么?似乎有很多关于不同部分的具体问题,但没有明确和简单的例子。
【问题讨论】:
Getting Text from a URL | Example Depot:
try {
// Create a URL for the desired page
URL url = new URL("http://hostname:80/index.html");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
当谈到“写入”到一个 URL 时,我想你会想要像 Sending a POST Request Using a URL | Example Depot 这样的东西。
【讨论】:
你可以简单地使用这个:
InputStream stream = new URL( "http://google.com" ).openStream();
【讨论】:
Sun Microsystems 实际上有一个关于这个主题的tutorial on reading and writing with a URLConnection,这将是一个很好的起点。
【讨论】:
SB 链接到的Sun Microsystems article 将是一个不错的起点。但是,我绝对不会将其称为首选方式。首先它不必要地抛出异常,然后它不会在 finally 中关闭流。此外,它使用了我不同意的url.openStream 方法,因为即使HTTP error is returned 仍然可以接收输出。
我们写的不是url.openStream:
HttpURLConnection conn=(HttpURLConnection) url.openConnection()
//Any response code starting with 2 is acceptable
if(!String.valueOf(conn.getResponseCode()).startsWith('2'))
//Provide a nice useful exception
throw new IOException("Incorrect response code "+conn.getResponseCode()+" Message: " +getResponseMessage());
InputStream rawIn=conn.getInputStream()
OutputStream rawOut=conn.getOutputStream()
//You may want to add buffering to reduce the number of packets sent
BufferedInputStream bufIn=new BufferedInputStream(rawIn);
BufferedOutputStream bufOut=new BufferedInputStream(rawOut);
请勿在未处理异常或关闭流的情况下使用此代码!。这实际上很难正确地做到。如果您想了解如何正确执行此操作,请查看my answer 到fetching images in Android 的更具体的问题,因为我不想在这里全部重写。
现在,当从服务器检索输入时,除非您正在编写命令行工具,否则您需要在单独的线程中运行它并显示加载对话框。 Sgarman's answer 使用基本的 Java 线程演示了这一点,而我的 an answer 使用 Android 中的 AsyncTask 类使其更整洁。 class file 没有任何 Android 依赖项,并且许可证是 Apache,因此您可以在非 Android 项目中使用它。
【讨论】: