2012-05-14 9 views
1

我只是想獲得解析數據頁面的來源。
我用下面的代碼
不能得到一個頁面的全部源android

public static String getPageSourceFromUrl(String Url) { 
     String text = ""; 
     try { 
      HttpClient client = new DefaultHttpClient(); 
      HttpGet request = new HttpGet(Url); 
      HttpResponse response = client.execute(request); 
     InputStream in = response.getEntity().getContent(); 
     BufferedReader reader = new BufferedReader(
       new InputStreamReader(in)); 

     StringBuilder str = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      str.append(line); 
     } 
     in.close(); 
     text = str.toString(); 
    } catch (Exception ex) { 

    } 
    return text; 
} 

和頁面是:「http://vn.answers.yahoo.com/question/index?qid=20111022210730AAWvfKI

不幸的是,在某些頁面(如上圖所示),文字的回報只是整個源的一部分。也許字符串超過了限制,所以任何人都有解決辦法?

+0

你設法解決這個問題? – erdomester

+0

對不起,這是很久以前,所以我不記得我會問這裏:( –

+0

然後請接受我的解決方案,我能夠解決這個問題。 – erdomester

回答

0

我設法解決(我們)的問題。優雅的方式是創建一個類:

public class GetRating { 

    public GetRating(){ 

    } 

    public String GetRatingFromURL(String url){ 

     HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
     HttpGet httpget = new HttpGet(url); // Set the action you want to do 
     HttpResponse response = null; 
     try { 
      response = httpclient.execute(httpget); 
     } catch (ClientProtocolException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } // Executeit 


     HttpEntity entity = response.getEntity(); 
     InputStream is = null; 


     try { 
      is = entity.getContent(); 
     } catch (IllegalStateException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } // Create an InputStream with the response 


     BufferedReader reader = null; 
     try { 
      reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
     } catch (UnsupportedEncodingException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 


     StringBuilder sb = new StringBuilder(); 
     String line = null; 


     try { 
      while ((line = reader.readLine()) != null) // Read line by line 
       sb.append(line + "\n"); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

     String resString = sb.toString(); // Result is here 


     return resString; 


    } 


} 

然後從另一個類調用它:

GetRating GN = new GetRating(); 
String pagesource = GN.GetRatingFromURL(url)("http://somewebpage.com"); 
相關問題