android中访问 webView加载URL时的response数据

原创
2014/03/20 19:47
阅读数 2.9W

不多说直接上代码:

1、activity 的onCreate 方法,从布局中得到WebView引用,并设置相关参数 <!-- lang: java --> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = (WebView) findViewById(R.id.web_view); webView.loadUrl("http://www.baidu.com"); webView.setWebViewClient(new MyWebViewClient()); webView.setWebChromeClient(new WebChromeClient()); } 2、MyWebViewClient 继承WebViewClient,并重写public boolean shouldOverrideUrlLoading(WebView view, String url)方法。简单的说就是,通过HttpClient 来请求URL,获取到相应的response,从response中就可以得到所有你想要的数据了;当然,要通过WebView.loadData()方法将response的entity加载到WebView中,这样控件才能显示web页面:

<!-- lang: java -->
private class MyWebViewClient extends WebViewClient {

	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		Log.d("info", "===>>> shouldOverrideUrlLoading method is called!");
		// TODO Auto-generated method stub
		URL local_url;
		URLConnection connection;
		try {
			local_url = new URL(url);
			connection = local_url.openConnection();
			connection.setConnectTimeout(15000);
			connection.connect();
		} catch (Exception e) {}

		final HttpGet httpGet = new HttpGet(url);

		Thread theard = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					HttpResponse response;
					String htmlContent;
					HttpClient httpClient = new DefaultHttpClient();
					response = httpClient.execute(httpGet);
					if (response.getStatusLine().getStatusCode() == 200) {
						Header[] headers = response.getAllHeaders();
						for (Header header : headers) {
							String name = header.getName();
							String value = header.getValue();
							Log.d("info", "===>>> name:" + name);
							Log.d("info", "===>>> value:" + value);
						}
						HttpEntity entity = response.getEntity();
						if (entity != null) {
							InputStream inputStream = entity.getContent();
							htmlContent = convertToString(inputStream);
							Log.d("info", "===>>> htmlContent:" + htmlContent);
							webView.loadData(htmlContent, "text/html", "utf-8");
						}
					}
				} catch (Exception e) {
				};
			}
		});
		theard.start();

// view.loadData(htmlContent, "text/html", "utf-8"); return true; // return super.shouldOverrideUrlLoading(view, url); }

	public String convertToString(InputStream inputStream) {
		StringBuffer string = new StringBuffer();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream));
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				string.append(line + "\n");
			}
		} catch (IOException e) {
		}
		return string.toString();
	}
}

注:我不是Java开发者,也不是Android开发者,代码写的丑的地方将就着看;另,欢迎扔砖…… ^_^

展开阅读全文
打赏
0
3 收藏
分享
加载中
伟才,略过~~~
2014/12/22 15:09
回复
举报
更多评论
打赏
1 评论
3 收藏
0
分享
返回顶部
顶部