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

时间:2010-05-27 14:54:53

标签: android http file

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

您可以提供任何帮助。

3 个答案:

答案 0 :(得分:57)

尝试以下方法:

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: Getting text from URL

应该在Android上运行良好。

答案 1 :(得分:14)

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

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

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

请注意,您几乎不应该只使用URL.openStream(不设置某些配置,如超时),尽管许多示例都表明,因为如果服务器不可用,它将无限期地阻塞(默认情况下,它没有超时):URL.openStream() Might Leave You Hanging

答案 2 :(得分:5)

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