【问题标题】:How can I make a http partial GET request in Java如何在 Java 中发出 http 部分 GET 请求
【发布时间】:2023-04-02 15:04:01
【问题描述】:

我正在尝试发出部分 GET 请求,我希望得到 206 响应,但我仍然得到 200 OK。我怎样才能让它以 206 响应?

这是我写的代码:

HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

int start = Integer.parseInt(args[1]);
int end = Integer.parseInt(args[2]);

urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("Range", "bytes=" + start + "-" + end);

if (urlConn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL)
    System.out.println ("File cannot be downloaded.");          
else    
{                                   
    String filepath = url.getPath();
    String filename = filepath.substring (filepath.lastIndexOf('/') + 1);

    BufferedInputStream in = new BufferedInputStream (urlConn.getInputStream());
    BufferedOutputStream out = new BufferedOutputStream (new FileOutputStream (filename));

    int temp;    
    while ((temp = in.read()) != -1)
    {
        out.write ((char)temp);
    }

    out.flush();
    out.close();

    System.out.println ("File downloaded successfully.");
}

【问题讨论】:

    标签: java http get partial


    【解决方案1】:

    我怎样才能让它以 206 响应?

    您不能强制服务器尊重您的 Range 标头。 HTTP 1.1 规范says

    "服务器可以忽略 Range 标头。"


    你的评论:

    我知道服务器不会忽略它。至少不应该

    显然,服务器 >>IS

    【讨论】:

    • 我知道服务器不会忽略它。至少不应该。
    • 我有一个循环来检查范围是否包含整个文档。好吧,至少我看到你说代码可以满足我的目的,但问题出在其他问题上。
    猜你喜欢
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多