在Android上从服务器读取文本文件

我的服务器上有一个文本文件。 我想从我的Android应用程序打开文本文件,然后在TextView中显示文本。 我找不到任何如何与服务器进行基本连接并将数据提供给string的示例。

任何帮助,您可以提供将不胜感激。

尝试以下操作:

try { // Create a URL for the desired page URL url = new URL("mysite.com/thefile.txt"); // 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) { } 

(来自Exampledepot:从URL获取文本 )

应该在Android上运行良好。

虽然URL.openStream可以工作,但最好使用Android for HTTP附带的Apache HttpClient库。 除了其他原因,你可以使用内容编码(gzip),这将使文本文件传输小得多(电池寿命更长,净使用量更less)和更快。

有很多方法可以使用HttpClient,并且存在几个帮助程序来包装事物并使其更容易。 看到这个post的更多细节: Android项目使用httpclient – > http.client(apache),post / get方法 (并注意我包含的HttpHelper确实使用gzip,但不是全部)。

另外,无论您使用何种方法通过HTTP检索数据,您都需要使用AysncTask (或Handler)来确保在进行networking调用时不会阻塞UI线程。

并注意,你应该几乎不使用URL.openStream(没有设置一些configuration,如超时),虽然很多例子显示,因为它将无限期阻塞,如果你的服务器不可用(默认情况下,它没有超时): URL.openStream()可能会让你挂起 。

使用networking资源时不要忘记将清单上的Internet权限添加到清单:(添加清单)。