2011-11-18 33 views
0

我有一個android應用程序,我需要獲取將在webview中加載的頁面的HTML代碼。這個代碼我需要甚至在web頁面加載之前得到它,並採取相應的行動。如何獲取將在webview中加載的頁面的HTML代碼?

我試圖捕捉將在方法

「公共無效onPageStarted(的WebView視圖,字符串URL,位圖圖標)」

加載的URL但是,什麼是讓HTML的方式將在webview中加載的頁面的代碼?

回答

0

我不知道怎麼弄的WebView內容,但我用這對網頁

HttpClient httpClient = new DefaultHttpClient(); 
HttpContext localContext = new BasicHttpContext(); 
HttpGet httpGet = new HttpGet("website url"); 
HttpResponse response = httpClient.execute(httpGet, localContext); 
String result = ""; 

BufferedReader reader = new BufferedReader(
    new InputStreamReader(
     response.getEntity().getContent() 
    ) 
); 

String line = null; 
while ((line = reader.readLine()) != null){ 
    result += line + "\n"; 

} 

第二種方法是的代碼,

URL url; 
    try { 
     // url = new URL(data.getScheme(), data.getHost(), data.getPath()); 
     url = new URL("website url"); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(
       url.openStream())); 
     String line = ""; 
     while ((line = rd.readLine()) != null) { 
      text.append(line); 
     } 

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

這是不是拿到視圖內容合作它了有用的,只有獲得網頁響應。 –

0

我不找到任何webview函數來獲取HTML數據。我發現這很有用。

try { 
      URL twitter = new URL(
        "http://www.stackoverflow.com"); 
      URLConnection tc = twitter.openConnection(); 
      BufferedReader in = new BufferedReader(new InputStreamReader(
        tc.getInputStream())); 

      String htmlData = ""; 
      String line; 
      while ((line = in.readLine()) != null) { 
        htmlData = htmlData+"\n"+line; 
      } 
     } catch (MalformedURLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
2

利用的HttpClient:

public String httpGet(String url) throws URISyntaxException, 
     ClientProtocolException, IOException { 
     try { 

     HttpGet request = new HttpGet(); 

     request.setURI(new URI(url)); 
     response = client.execute(request); 

     htmlBody = EntityUtils.toString(response.getEntity()); 

     } catch (Exception ex) { 
     } 

     return htmlBody; 
    } 

而且有兩種方式顯示在WebView中它的,無論是從文件(那麼你應該保存有個設備上的HTML文件,這使得內容可脫機):

myWebView.loadUrl("file://" 
           + Environment.getExternalStorageDirectory() 
           + "/filename.html"); 

或者你喂的WebView一個字符串HTML:

myWebView.loadData(HTMLString, "text/html", "utf-8"); 

在這裏你會發現我寫的全HttpClient的,一些你可能需要的功能,有的不是:

http://droidsnip.blogspot.com/2011/10/custom-http-client-android.html#more

相關問題