java - Apache HttpClient 获取添加字节范围 header ?

标签 java android apache

有谁知道如何在 HTTP 请求中请求字节范围?我希望通过请求下载停止位置的字节范围并从 getContent() 读取其 InputStream 来促进我们应用程序中的下载恢复。

我尝试遍历标题,但它们为空。来源如下。

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

凯文

最佳答案

我可以通过添加以下行来实现此功能:

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

关于java - Apache HttpClient 获取添加字节范围 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7362719/

相关文章:

android - 在 Android 应用程序的帐户和同步菜单下显示设置

php - Apache 404 文件匹配

wordpress - 在此服务器上找不到请求的 URL/wordpress/

html - 很棒的字体没有加载到我的 apache 中

android - 在调试apk正常工作时 react native 版本apk在启动时崩溃

android - 编辑文本提示折叠

java - 构造函数中的继承

java - 无法使用 XOM 解析元素属性

java - 谷歌应用引擎 : How to uniquely identify JVMs instances/measure parallelism?

java - Spark 2.6.0 : Exception in thread "main" java. lang.ClassNotFoundException: <Main Class> 当 <Main Class> 位于提交到集群的 jar 中时