2012-06-05 85 views

回答

2
HttpClient client = new DefaultHttpClient(); 
HttpGet request = new HttpGet(url); 
HttpResponse response = client.execute(request); 

String html = ""; 
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(); 
html = str.toString(); 

不要忘記添加Internet權限在AndroidManifest:

<uses-permission android:name="android.permission.INTERNET" /> 

您可以參考這些鏈接以獲得更多幫助:

http://lexandera.com/2009/01/extracting-html-from-a-webview/

Is it possible to get the HTML code from WebView

How to get the html-source of a page from a html link in android?

+0

工作就像一個魅力! :)謝謝:D –

+0

我如何得到一些網頁的html源代碼?如果我獲得完整的源頁面,它可能會花費很多時間,我不需要獲得所有的線路,你能幫助我嗎? thx非常多 –

1

您需要HttpClient才能執行HttpGet請求。然後您可以閱讀該請求的內容。

這個片段給你一個InputStream

public static InputStream getInputStreamFromUrl(String url) { 
    InputStream content = null; 
    try { 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpResponse response = httpclient.execute(new HttpGet(url)); 
    content = response.getEntity().getContent(); 
    } catch (Exception e) { 
    Log.e("[GET REQUEST]", "Network exception", e); 
    } 
    return content; 
} 

而這個方法返回String

// Fast Implementation 
private StringBuilder inputStreamToString(InputStream is) { 
    String line = ""; 
    StringBuilder total = new StringBuilder(); 

    // Wrap a BufferedReader around the InputStream 
    BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 

    // Read response until the end 
    while ((line = rd.readLine()) != null) { 
     total.append(line); 
    } 

    // Return full string 
    return total; 
} 

來源:http://www.androidsnippets.com/executing-a-http-get-request-with-httpclienthttp://www.androidsnippets.com/get-the-content-from-a-httpresponse-or-any-inputstream-as-a-string

+0

你能告訴如何將html代碼顯示到textview中嗎?我試過了,它沒有奏效!它意外停止! @Kiril –

+1

我假設你已經在佈局中定義了一個TextView。現在你可以通過使用TextView yourTextView =(TextView)findViewById(R.id.NameOfYourTextView)來訪問TextView;'之後你可以調用方法'yourTextView.setText(「HTML code」);' 編輯:同時請查看下面的提取HTML代碼的答案 – Kiril

+0

@Kiril - 我如何得到一些網頁的html源代碼?如果我獲得完整的源頁面,它可能會花費很多時間,我不需要獲得所有的線路,你能幫助我嗎? thx非常 –

-1

使用上面的代碼,並將其設置爲像這樣的文本視圖:

InputStream is =InputStream getInputStreamFromUrl("http://google.com"); 
String htmlText = inputStreamToString(is); 

mTextView.setText(Html.fromHtml(htmlText)); 

但做網絡請求在一個單獨的線程/ asynctask :)