2010-01-19 116 views
8

我有下面的代碼,它讀取URLURL的Android的閱讀內容(內容後失蹤的結果)

public static String DownloadText(String url){ 
    StringBuffer result = new StringBuffer(); 
    try{ 
     URL jsonUrl = new URL(url); 

     InputStreamReader isr = new InputStreamReader(jsonUrl.openStream()); 

     BufferedReader in = new BufferedReader(isr); 

     String inputLine; 

     while ((inputLine = in.readLine()) != null){ 
      result.append(inputLine); 
     } 
    }catch(Exception ex){ 
     result = new StringBuffer("TIMEOUT"); 
     Log.e(Util.AppName, ex.toString()); 
    } 
     in.close(); 
     isr.close(); 
    return result.toString(); 
} 

問題的內容是我缺少的內容後的結果4065個字符返回。有人可以幫我解決這個問題嗎?

注: 我試圖讀取的url包含一個json響應,所以一切都在一行我認爲這就是爲什麼我有一些內容丟失。

+0

嗨,我有同樣的問題。你能幫助我嗎?你做了什麼糾正? – Praveen 2010-03-15 09:37:16

+0

我還沒有找到這個問題的解決方案。 – Josnidhin 2010-03-16 02:20:16

+0

如何使用HttpClient?我的意思是org.apache.http.client.HttpClient。 – skysign 2010-02-01 07:35:20

回答

10

試試這個:

try { 
    feedUrl = new URL(url).openConnection(); 
} catch (MalformedURLException e) { 
    Log.v("ERROR","MALFORMED URL EXCEPTION"); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
try { 
    in = feedUrl.getInputStream(); 
    json = convertStreamToString(in); 
}catch(Exception e){} 

而convertStreamToString是:

private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    try { 
    while ((line = reader.readLine()) != null) { 
     sb.append(line + "\n"); 
    } 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } finally { 
    try { 
     is.close(); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 
} 
return sb.toString(); 
} 
3

這裏是一個清潔的版本來獲取腳本從網絡輸出:

public String getOnline(String urlString) { 
    URLConnection feedUrl; 
    try { 
     feedUrl = new URL(urlString).openConnection(); 
     InputStream is = feedUrl.getInputStream(); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 

     while ((line = reader.readLine()) != null) { 
      sb.append(line + ""); 
     } 
     is.close(); 

     return sb.toString(); 

    }catch(Exception e){ 
     e.printStackTrace(); 
    } 

    return null; 
} 

記住你不能從主線程下載任何東西。它必須來自一個單獨的線程。使用類似的東西:

new Thread(new Runnable(){ 
      public void run(){ 

       if(!isNetworkAvailable()){ 
        Toast.makeText(getApplicationContext(), getResources().getString(R.string.nointernet), Toast.LENGTH_LONG).show(); 
        return; 
       } 

       String str=getOnline("http://www.example.com/script.php"); 

      } 
     }).start(); 
+0

我可否知道這種方法是否忽略空行並進入? – user1788736 2017-11-30 02:59:55