WebResourceResponse无法从HttpConnection(Android)读取完整的输入流 [英] WebResourceResponse can't read full inputstream from HttpConnection (Android)

查看:75
本文介绍了WebResourceResponse无法从HttpConnection(Android)读取完整的输入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用可以播放一些视频的离子应用程序(例如混合动力系统).我想在请求中添加一些标头,以便覆盖"shouldInterceptRequest".

I'm working with an ionic application(like hybrid) which can play some videos.I want to add some headers to the request so that I override the "shouldInterceptRequest".

URL myUrl = new URL(real);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
for (Map.Entry < String, String > entry: headers.entrySet()) {
  connection.setRequestProperty(entry.getKey(), entry.getValue());
}
InputStream in = connection.getInputStream();
WebResourceResponse response = new WebResourceResponse("video/mp4", "UTF-8", in );
for (Map.Entry < String, List < String >> entry: connection.getHeaderFields().entrySet()) {
  resHeaders.put(entry.getKey(), entry.getValue().get(0));
}

此代码无效.html中的video标签无法播放视频.所以我添加了一些代码.

This code can't work.The video tag in html can't play the video. So I add some code.

byte[] bytes = new byte[30 * 1024 * 1024];
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(bytes)) != -1) {
  byteBuffer.write(bytes, 0, len);
}
bytes = byteBuffer.toByteArray();
WebResourceResponse response = new WebResourceResponse("video/mp4", "UTF-8", new ByteArrayInputStream(bytes));

当我将输入流读取为字节并将字节发送到WebResourceResponse时,可以播放视频.但是,这意味着如果视频很大,我的应用程序将占用大量内存.

When I read inputstream into bytes and send bytes to WebResourceResponse, the video can be play.However it means my application will use lots of memory if the video is large.

因此,我想知道有什么方法可以在不将输入流保存为字节的情况下播放视频.

So that, I want to know is there any way to play the video without saving inputstream into bytes.

推荐答案

好的.最后,我找到了方向.实际上,我的目标是向资源请求中添加自定义标头,现在我发现有一种更简单的方法.例如,如果要加载图像,则将使用这样的img标签,< img src ="the_url_of_image"> ,除非我不向我添加任何标头拦截请求.但是,我们现在可以使用 blob .我们可以使用ajax之类的资源来请求资源,并使用 createObjectURL 创建指向该资源的url链接.

OK.Fianlly,I found my way. Actually, my goal is to add custom headers to resource request and now I found there is an easier way to do it. For example, if I want to load a image,I will use img tag like this,<img src="the_url_of_image">,and I can't add any header to the request unless I interecept the request. However,we can use blob now.We can request the resource by using something like ajax and use createObjectURL to create a url links to the resource.

这篇关于WebResourceResponse无法从HttpConnection(Android)读取完整的输入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆