我使用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);
}