在Android浏览器中获取字符串形式的HTML文档,可以通过以下步骤实现:
以下是一个示例代码,演示如何在Android浏览器中获取字符串形式的HTML文档:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl("https://www.example.com");
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
new GetHtmlTask().execute(url);
return true;
}
}
private class GetHtmlTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String html = "";
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
html = stringBuilder.toString();
reader.close();
inputStream.close();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return html;
}
@Override
protected void onPostExecute(String html) {
// 在这里可以使用获取到的html字符串进行后续处理
}
}
}
这是一个简单的示例代码,通过WebView加载网页并获取其HTML内容。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云