簡體   English   中英

如何在Android中從URL讀取文本文件(非HTML)?

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

我從服務器請求一個文本文件。 網址不會以some_file.txt結尾,因為該文件是根據請求動態創建的(不確定是否確實相關)。 當我使用下面的代碼時,我不會讀入文本(盡管我確實以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;

這僅返回“ RESULTS:”,但不返回任何文本。 我想念什么?

編輯:這是文件的示例。 如果將網址粘貼到地址欄中,則會在瀏覽器中顯示:

20120120_1734
20120120_1725
20120120_1715
20120120_1705
20120120_1655

您正在吞噬解決此問題所需的所有潛在錯誤。

在catch子句中,嘗試添加一些代碼以查看錯誤。 類似於以下內容:

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

您是否在清單中添加了Internet權限? 代碼看起來不錯,但是由於在catch子句中沒有打印消息,因此您顯然會遇到一些錯誤,並且不會輸出錯誤。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM