2015-10-24 55 views
0

我一直在我們的應用程序中使用NanoHTTPD來提供內容,包括從本地SDCard到Web視頻的音頻和視頻。內容範圍和內容長度標題以及HTTP狀態已正確配置。現在,我們有一個用例,我們想通過NanoHTTPD在服務器上提供內容。Android NanoHTTPD流媒體內容持久連接

NanoHTTPD方法的問題是它讀取Webview請求的完整內容。在本地文件的情況下,它仍然是正常的,但您不能等待它從服務器獲取太多內容並刷新輸出流。

我正在尋找一種方法,我可以打開一個連接並繼續提供請求的部分數據。就像在請求中使用範圍標題獲取內容時一樣。連接保持打開狀態,視頻播放器一有足夠的緩衝區就會播放。

請幫忙。

回答

0

我使用HTTP Client解決了這個問題。我在具有唯一端口的localhost上註冊了一個模式,並通過添加適當的標題,狀態和內容長度來處理大型媒體的響應。這裏要做的三件事:

1)將HTTP響應的頭部複製到本地響應
2)設置響應代碼。全部內容(200)或部分內容(206)
3)創建一個新的InputStreamEntity並將其添加到響應中

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

    }