【问题标题】:How can I read a text file (not HTML) from URL in Android?如何从 Android 中的 URL 读取文本文件(不是 HTML)?
【发布时间】:2012-01-20 17:32:32
【问题描述】:

我从服务器请求一个文本文件。该 url 不以 some_file.txt 结尾,因为该文件是根据请求动态创建的(不确定这是否相关)。当我使用下面的代码时,我不会读入文本(虽然我会读入 html,如果指向具有 html 的 url)。

            String text = "RESULTS:\n";

            try {  

                String urlString = 
                    "http://appdata.mysite.com/httpauth/" +
                    "hub/DAR_param1_RTQB?" + 
                    "method=query&list=param2"; 

                // Create a URL 
                URL url = new URL(urlString);

                // Read all the text returned by the server
                in = new BufferedReader(new InputStreamReader(url.openStream()));

                String line;
                while ((line = in.readLine()) != null) {
                    text = text + line;
                }                    
            } catch (MalformedURLException e) {
            } catch (IOException e) {
            } catch (Exception e) {
            } finally {
                if ( in != null ) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        Log.e(TAG, "Exception trying to close BufferedReader");
                    }
                }
            } 

            return text;

这仅返回“结果:”,但不返回任何文本。我错过了什么?

编辑:这是文件的一个示例。如果将 url 粘贴到地址栏中,则会在浏览器中显示:

20120120_1734
20120120_1725
20120120_1715
20120120_1705
20120120_1655

【问题讨论】:

  • 您能否发布一个此请求将生成的文件示例?
  • @DanW 我编辑了我的原始帖子以显示文件。
  • @Hap 如果你只想显示它,为什么现在使用 WebView?

标签: java android file url io


【解决方案1】:

您正在接受解决此问题所需的所有潜在错误。

在您的 catch 子句中,尝试添加一些代码来查看错误。 大致如下:

System.out.println("Error: ", e.getMessage());

【讨论】:

  • 好的。好点子。我得到一个未找到文件的异常。原来是身份验证问题。
【解决方案2】:

您是否在清单中添加了 Internet 权限?代码看起来不错,但是您显然遇到了一些错误并且没有输出错误,因为您在 catch 子句中没有打印消息。

Log.i("--->","e.getMessage()); //just like oldingn said 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2011-02-23
    相关资源
    最近更新 更多