2

我需要在 Java 中使用 HTTP“部分获取请求”消息,但在 Internet 上找不到任何答案。

实际上,我知道如何发送“获取”消息,但我不知道如何发送“部分获取”消息。

下面的代码显示了一些信息:

      else if(args.length == 0){ // 5 OLACAK
            con.setRequestMethod("HEAD");

            fromURL = new BufferedInputStream(con.getInputStream(), bufSize);
            toFile = new BufferedOutputStream(new FileOutputStream(outputFile), bufSize);

            if(con.getResponseCode() == HttpURLConnection.HTTP_OK){

                byte startRange =  0; //Byte.parseByte(args[3]);
                byte finishRange =  25;//Byte.parseByte(args[4]);

                if(startRange < 0 || finishRange > ((byte)con.getContentLength())
                        || startRange > finishRange){
                    System.out.println("Range is not OK.");
                }else{                     

                ////////////////////////////////////////////////////
                ////////////////////////////////////////////////////
                //
                // I need to send a partial get message here 
                // Range should in between [startRange, finishRange]
                //
                ////////////////////////////////////////////////////
                ////////////////////////////////////////////////////

                }
            }
        }
4

1 回答 1

1

你的代码到处都是,所以很难弄清楚你在自己的个人研究中的位置。但是让我们假设您已经知道服务器端资源支持范围请求 - 要发送部分 GET 您只需要做两件事:

  1. 包括一个Range:标题与您正在寻找的范围的开始和结束
  2. 处理响应,注意服务器返回“206 - 部分内容”的状态代码

一些伪代码:

conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.addRequestProperty("Range", "bytes=0-25");
BufferedReader reader = new BufferedReader(new InputStreamReader(
        conn.getOutputStream()));
if(conn.getResponseCode() == 206) {
    // process stream here
}
于 2013-03-09T14:18:18.693 回答