如何在Java中创建http部分GET请求

时间:2013-03-17 13:34:04

标签: java http get partial

我正在尝试发出部分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.");
}

1 个答案:

答案 0 :(得分:1)

  

如何用206来回复?

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

  

服务器可以忽略Range标头。


你发表评论:

  

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

显然,服务器>> IS<<忽略标题。或者,您请求的范围包含整个文档。