Reading Text File From Server on Android

2019-01-03 02:19发布

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. I cannot find any examples of how to do a basic connection to a server and feed the data into a String.

Any help you can provide would be appreciated.

3条回答
仙女界的扛把子
2楼-- · 2019-01-03 03:03

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)

Should work well on Android.

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-03 03:09

Don't forget to add internet permissions to the manifest when taking net resources: (add in manifest).

查看更多
Bombasti
4楼-- · 2019-01-03 03:20

While URL.openStream will work, you would be better off using the Apache HttpClient library that comes with Android for 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.

There are various ways to use HttpClient, and several helpers exist to wrap things and make it easier. 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).

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.

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.

查看更多
登录 后发表回答