本文介绍了Apache的HttpClient的获取附加一个字节范围头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何请求字节与HTTP请求的范围来吗?我期待通过请求在哪里下载不放过一个字节范围和getContent()以读取它的InputStream,方便的下载我们的应用程序的断点续传。

Does anyone know of how to request byte ranges along with an HTTP request? I am looking to facilitate the resuming of downloads in our application by requesting a byte range of where the download left off and reading its InputStream from getContent().

我试过遍历头,但他们都为空。来源如下。

I tried iterating over the headers but they are null. Source is below.

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

/**
 * @author Kevin Kowalewski
 *
 */
public class DownloadClient {
DefaultHttpClient httpClient;
HttpGet httpGet;
HttpResponse httpResponse;
HttpEntity httpEntity;
InputStream httpInputStream;

private static String LOG_TAG = DownloadClient.class.getName();

public DownloadClient(){
    httpClient = new DefaultHttpClient();
    httpGet = new HttpGet("http://cachefly.cachefly.net/100mb.test");
    for (Header header : httpGet.getAllHeaders()){
        Log.d(LOG_TAG, "--> Header: " + header);
    }

    Log.d(LOG_TAG, "--> Header size is: " + httpGet.getAllHeaders().length);
    try {
        httpResponse = httpClient.execute(httpGet);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    httpEntity = httpResponse.getEntity();
    try {
        httpInputStream = httpEntity.getContent();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.d(LOG_TAG, "--> StatusLine: " + httpResponse.getStatusLine());
}

public void read(){
    byte[] readBuffer = new byte[32];
    try {
        while (httpInputStream.read(readBuffer) != -1){
            try{Thread.sleep(100);}catch(Exception e){}
            //Log.d(LOG_TAG,"--> Read Bytes: " + new String(readBuffer));
        };
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public void shutdown(){
    httpGet.abort();
    httpClient.getConnectionManager().shutdown();
}

}

凯文

推荐答案

我可以通过添加以下行来得到这个工作:

I was able to get this working by adding the following line:

httpGet.addHeader("Range", "bytes=0-0");

这篇关于Apache的HttpClient的获取附加一个字节范围头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 00:51