首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安卓NanoHTTPD流媒体内容长连接

安卓NanoHTTPD流媒体内容长连接
EN

Stack Overflow用户
提问于 2015-10-25 00:21:29
回答 1查看 595关注 0票数 0

我一直在我们的一个应用程序中使用NanoHTTPD来提供内容,包括从本地SDCard到Webview的音频和视频。已正确配置内容范围和内容长度标头以及HTTP状态。现在,我们有了一个想要通过NanoHTTPD在服务器上提供内容的用例。

NanoHTTPD方法的问题在于它读取Webview请求的完整内容。对于本地文件,它仍然可以,但您不能等待它从服务器获取如此多的内容并刷新输出流。

我正在寻找一种方法,在这种方法中,我能够打开连接,并继续为请求返回的部分数据提供服务。就像在请求中获取带有range头的内容一样。连接保持打开,只要有足够的缓冲区,视频播放器就会立即播放。

请帮帮忙。

EN

回答 1

Stack Overflow用户

发布于 2015-10-27 22:14:43

我通过使用HTTP客户端解决了这个问题。我在localhost上注册了一个具有唯一端口的模式,并通过添加适当的报头、状态和内容长度来处理大型媒体的响应。这里有三件事要做:

1)将报头从HTTP响应复制到本地响应

2)设置响应码。完整内容(200)或部分内容(206)

3)创建新的InputStreamEntity并添加到响应中

代码语言:javascript
复制
@Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
        String range = null;
        //Check if there's range in request header 
        Header rangeHeader = request.getFirstHeader("range");

        if (rangeHeader != null) {
            range = rangeHeader.getValue();
        }

        URL url = new URL(mediaURL);
        URLConnection urlConn = url.openConnection();

        if (!(urlConn instanceof HttpURLConnection)) {
            throw new IOException("URL is not an Http URL");
        }
        HttpURLConnection httpConn = (HttpURLConnection) urlConn;
        httpConn.setRequestMethod("GET");

        //If range is present, direct HTTPConnection to fetch data for that range only    
        if(range!=null){
            httpConn.setRequestProperty("Range",range);
        }
        //Add any custom header to request that you want and then connect.
        httpConn.connect();

        int statusCode = httpConn.getResponseCode();

        //Copy all headers with valid key to response. Exclude content-length as that's something response gets from the entity. 
        Map<String, List<String>> headersMap =  httpConn.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : headersMap.entrySet())
        {
            if(entry.getKey() != null && !entry.getKey().equalsIgnoreCase("content-length")) {
                for (int i = 0; i < entry.getValue().size(); i++) {
                    response.setHeader(entry.getKey(), entry.getValue().get(i));
                }
            }
        }

        //Important to set correct status code
        response.setStatusCode(statusCode);

        //Pass the InputStream to response and that's it.
        InputStreamEntity entity = new InputStreamEntity(httpConn.getInputStream(), httpConn.getContentLength());
        entity.setContentType(httpConn.getContentType());
        response.setEntity(entity);

    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33320425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档