【问题标题】:HTTP "Partial" Get Request Message in JavaJava中的HTTP“部分”获取请求消息
【发布时间】:2013-03-09 13:26:26
【问题描述】:

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

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

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

      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]
                //
                ////////////////////////////////////////////////////
                ////////////////////////////////////////////////////

                }
            }
        }

【问题讨论】:

    标签: java url bytearray httpurlconnection urlconnection


    【解决方案1】:

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

    1. 在您正在寻找的范围的开始和结束处包含一个 Range: 标头
    2. 处理响应,注意服务器应该返回状态代码“206 - Partial Content”

    一些伪代码:

    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
    }
    

    【讨论】:

    • 在 java 中,如何向 setRequestMethod() 添加范围。我无法弄清楚那部分。感谢您的回复。
    • 您不将其添加到setRequestMethod,而是指定Range: 标头(我已经在答案中说明了如何操作)。
    • 那个伪代码真的很有帮助,再次感谢您的回复。
    猜你喜欢
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2018-06-25
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多