简体   繁体   English

如何在Android中从URL读取文本文件(非HTML)?

[英]How can I read a text file (not HTML) from URL in Android?

I request a text file from a server. 我从服务器请求一个文本文件。 The url does not end in some_file.txt, because the file is created dynamically per the request (not sure if that is even relevant). 网址不会以some_file.txt结尾,因为该文件是根据请求动态创建的(不确定是否确实相关)。 When I use the code below, I do not read in the text (though I do read in html, if pointed to a url that has html). 当我使用下面的代码时,我不会读入文本(尽管我确实以html读取,如果指向的是具有html的网址)。

            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;

This returns only "RESULTS:", but none of the text. 这仅返回“ RESULTS:”,但不返回任何文本。 What am I missing? 我想念什么?

Edit: Here is an example of the file. 编辑:这是文件的示例。 This is displayed in a browser if the url is pasted into the address bar: 如果将网址粘贴到地址栏中,则会在浏览器中显示:

20120120_1734
20120120_1725
20120120_1715
20120120_1705
20120120_1655

You are swallowing all the potential errors that you need to see to troubleshoot this. 您正在吞噬解决此问题所需的所有潜在错误。

In your catch clauses, try adding some code to see the errors. 在catch子句中,尝试添加一些代码以查看错误。 Something along the lines of: 类似于以下内容:

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

Did you add the Internet permissions in the manifest? 您是否在清单中添加了Internet权限? The code looks fine, but you're clearly getting some error and not outputting the errors since you dont have a print message in the catch clause. 代码看起来不错,但是由于在catch子句中没有打印消息,因此您显然会遇到一些错误,并且不会输出错误。

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

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

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