简体   繁体   English

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

[英]Reading Text File From Server on Android

I have a text file on my server. 我的服务器上有一个文本文件。 I want to open the text file from my Android App and then display the text in a TextView. 我想从我的Android应用程序中打开文本文件,然后在TextView中显示文本。 I cannot find any examples of how to do a basic connection to a server and feed the data into a String. 我找不到任何如何与服务器进行基本连接并将数据提供给String的示例。

Any help you can provide would be appreciated. 您可以提供的任何帮助将不胜感激。

Try the following: 请尝试以下方法:

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) {
}

(taken from Exampledepot: Getting text from URL ) (取自Exampledepot:从URL获取文本

Should work well on Android. 应该在Android上运行良好。

While URL.openStream will work, you would be better off using the Apache HttpClient library that comes with Android for HTTP. 虽然URL.openStream可以工作,但最好还是使用Android附带的Apache HttpClient库来实现HTTP。 Among other reasons, you can use content encoding (gzip) with it, and that will make text file transfers much smaller (better battery life, less net usage) and faster. 除了其他原因,您可以使用内容编码(gzip),这将使文本文件传输更小(更长的电池寿命,更少的净使用)和更快。

There are various ways to use HttpClient, and several helpers exist to wrap things and make it easier. 有多种方法可以使用HttpClient,并且存在几个帮助程序来包装并使其更容易。 See this post for more details on that: Android project using httpclient --> http.client (apache), post/get method (and note the HttpHelper I included there does use gzip, though not all do). 有关详细信息,请参阅此帖子: 使用httpclient的Android项目 - > http.client(apache),post / get方法 (并注意我包含的HttpHelper确实使用gzip,但并非所有人都这样做)。

Also, regardless of what method you use to retrieve the data over HTTP, you'll want to use AysncTask (or Handler) to make sure not to block the UI thread while making the network call. 此外,无论您使用什么方法通过HTTP检索数据,您都希望使用AysncTask (或Handler)来确保在进行网络调用时不阻止UI线程。

And note that you should pretty much NEVER just use URL.openStream (without setting some configuration, like timeouts), though many examples show that, because it will block indefinitely if you the server is unavailable (by default, it has no timeout): URL.openStream() Might Leave You Hanging . 请注意,您几乎不应该只使用URL.openStream(不设置某些配置,如超时),尽管许多示例显示,因为如果服务器不可用(默认情况下,它没有超时),它将无限期地阻塞: URL.openStream()可能会让你挂起

在获取网络资源时,不要忘记向清单添加互联网权限:(添加清单)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM