webview 显示html文本,Webview仅显示某些页面上的原始HTML文本

我正在开发一个项目,我们有兴趣拦截来自WebView的一些HTTP流量,然后将一些额外的标头附加到请求,然后返回并在WebView中显示它.

为此,我们使用shouldInterceptRequest(WebView视图,String URL)方法,该方法返回webview应显示的WebResourceResponse.

这是我做的:

private WebResourceResponse handleRequest(String url){

Log.d(TAG, "Intercepting request at : " + url);

HttpURLConnection connection = null;

URL serverAddress = null;

WebResourceResponse response = null;

InputStream is = null;

String type = null;

String encoding = null;

int statusCode;

int length;

try

{

//Set up the initial connection

serverAddress = new URL(url);

connection = (HttpURLConnection)serverAddress.openConnection();

// Initiate a HEAD request to get meta data

connection.setRequestMethod("HEAD");

// Let the WebView handle requests with no headers in them.

Map> headers = connection.getHeaderFields();

if(headers == null){

Log.d(TAG, "Retrieved response with zero headers at: " + url);

return null;

}

statusCode = connection.getResponseCode();

if(statusCode == 200){

// OK, delegate request if content length is large enough

type = connection.getContentType();

encoding = connection.getContentEncoding();

length = connection.getContentLength();

Log.d(TAG, "ContentType = " + type + " encoding = " + encoding + " " + url);

connection.disconnect();

if(length > SIZE_THRESHOLD){

// send to other device

Log.d(TAG, "Delegating request to other device NOT IMPLEMENTED");

// TODO: Currently just handling them locally.

}

else{

connection = (HttpURLConnection)serverAddress.openConnection();

connection.setRequestMethod("GET");

is = connection.getInputStream();

statusCode = connection.getResponseCode();

type = connection.getContentType();

encoding = connection.getContentEncoding();

Log.d(TAG, "Done Loading " + url);

return new WebResourceResponse(type, encoding, is);

}

}

}

catch (MalformedURLException e) {

e.printStackTrace();

}

catch (ProtocolException e) {

e.printStackTrace();

}

catch (IOException e) {

Log.d(TAG, "IOException when connection to : " + url + " Stacktrace: " + Log.getStackTraceString(e));

}

return response;

}

如果我尝试加载像"www.madopskrifter.nu"或"www.newz.dk"这样的页面,那么我可以很好地了解所显示的图片和所有内容.但是,如果我浏览到stackoverflow之类的页面,我只需在stackoverflow.com上获取HTML索引文件.youtube.com也是如此.(我确实在WebView设置中启用了JavaScript)

有什么我想念的吗?目前我甚至没有添加自己的标题或任何东西,我只是明显地返回相同的响应,除了我"手动"获取它们.(此外我现在还没有处理零标题的请求,但即使我注释掉该代码,那么问题仍然存在).

任何帮助将不胜感激,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值