Java 使用InputStream进行随机访问

Java 使用InputStream进行随机访问,java,httprequest,inputstream,apache-httpclient-4.x,Java,Httprequest,Inputstream,Apache Httpclient 4.x,我有一个项目,我想从一个大文件下载单独的字节数组 目前,每次执行此操作时,我都会创建一个新的HttpRequest,并对范围使用setHeader()方法 HttpGet request = new HttpGet(url.toString()); HttpClient client = HttpClientBuilder.create().build(); request.setHeader("Range", "bytes=0-1024"); HttpResponse response = c

我有一个项目,我想从一个大文件下载单独的字节数组

目前,每次执行此操作时,我都会创建一个
新的HttpRequest
,并对范围使用
setHeader()
方法

HttpGet request = new HttpGet(url.toString());
HttpClient client = HttpClientBuilder.create().build();
request.setHeader("Range", "bytes=0-1024");
HttpResponse response = client.execute(request);
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Range", "bytes 10-20/1024");
InputStream is = response.getEntity().getContent();`
理想情况下,我会:

  • 从第10个字节开始流式传输
  • 读取10个字节
  • 从字节中获取一个整数n
  • 读取1024字节文件中间的某个字节 每次都不创建新的
    HttpRequest

    由于此内容范围的工作方式与我预期的不同,因此
    InputStream
    始终从文件的开头开始


    另外,
    inputstream.skip()
    对此不起作用,因为我不想下载所有字节

    为什么不对请求进行编码,以便收到一个“分块”响应,即每N个块保存一个“中断/放弃”过滤的流

    详情:

    对标题进行编码,以便获得分块响应

    如果需要,使用POST而不是GET强制“100 continue”标题进行响应。可能不需要,因此可以默认为GET

     http-outgoing-1 >> "POST /cre_mpg.php HTTP/1.1[\r][\n]"
     http-outgoing-1 >> "Content-Length: 309[\r][\n]"
     http-outgoing-1 >> "Host: 192.168.1.143[\r][\n]"
     http-outgoing-1 >> "Connection: Keep-Alive[\r][\n]"
     http-outgoing-1 >> "User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.5)[\r][\n]"
     http-outgoing-1 >> "Expect: 100-continue[\r][\n]"
     http-outgoing-1 >> "Content-Type: application/x-www-form-urlencoded; charset=UTF-8[\r][\n]"
     http-outgoing-1 >> "[\r][\n]"
    
    答复如下:

     http-outgoing-1 << "HTTP/1.1 100 Continue[\r][\n]"
     http-outgoing-1 << "[\r][\n]"
     http-outgoing-1 << HTTP/1.1 100 Continue
     http-outgoing-1 >> "infil1=http%3A%2F1.jpg&infil2=http%3A%36.flac&otfil=2036.mp4&t=3.00"
     http-outgoing-1 << "HTTP/1.1 200 OK[\r][\n]"
     http-outgoing-1 << "Server: nginx/1.6.0[\r][\n]"
     http-outgoing-1 << "Date: Fri, 09 May 2014 00:51:43 GMT[\r][\n]"
     http-outgoing-1 << "Content-Type: text/html[\r][\n]"
     http-outgoing-1 << "Transfer-Encoding: chunked[\r][\n]"
     http-outgoing-1 << "Connection: keep-alive[\r][\n]"
     http-outgoing-1 << "X-Powered-By: PHP/5.5.11-3+deb.sury.org~precise+1[\r][\n]"
     http-outgoing-1 << "[\r][\n]"
     http-outgoing-1 << "c1[\r][\n]"
    
    http-outgoing-1