WebResourceResponse can't read full inputstream from HttpConnection (Android)

不羁岁月 提交于 2021-01-29 08:31:53

问题


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));
}

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));

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.


回答1:


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.



来源:https://stackoverflow.com/questions/53332992/webresourceresponse-cant-read-full-inputstream-from-httpconnection-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!