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

Chr*_*ris 37 android http file

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

您可以提供的任何帮助将不胜感激.

aio*_*obe 58

请尝试以下方法:

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) {
}
Run Code Online (Sandbox Code Playgroud)

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

应该在Android上运行良好.

  • 注意:总是关闭`finally`块中的`Closeables`,因为这是确保即使抛出异常它们也会被关闭的唯一方法. (2认同)

Cha*_*ins 14

虽然URL.openStream可以工作,但最好还是使用Android附带的Apache HttpClient库来实现HTTP.除了其他原因,您可以使用内容编码(gzip),这将使文本文件传输更小(更长的电池寿命,更少的净使用)和更快.

有多种方法可以使用HttpClient,并且存在几个帮助程序来包装并使其更容易.有关详细信息,请参阅此帖子:使用httpclient的Android项目 - > http.client(apache),post/get方法(并注意我包含的HttpHelper确实使用gzip,但并非所有人都这样做).

此外,无论您使用什么方法通过HTTP检索数据,您都希望使用AysncTask(或Handler)来确保在进行网络调用时不阻止UI线程.

请注意,您几乎不应该只使用URL.openStream(不设置某些配置,如超时),尽管许多示例显示,因为如果服务器不可用(默认情况下,它没有超时),它将无限期地阻塞:URL.openStream()可能会让你挂起.


bar*_*tek 5

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

  • 这应该是一个评论 (5认同)