HTTP Get: Only download the header? (HEAD is not s

2020-03-14 18:02发布

问题:

In my code I use some Http Get request to download some files as a stream. I use the following code:

public String getClassName(String url) throws ClientProtocolException, IOException {
        HttpResponse response = sendGetRequestJsonText(url);

        Header[] all = response.getAllHeaders();
        for (Header h : all) {
            System.out.println(h.getName() + ": " + h.getValue());
        }

        Header[] headers = response.getHeaders("Content-Disposition");
        InputStreamParser.convertStreamToString(response.getEntity().getContent());
        String result = "";
        for (Header header : headers) {
            result = header.getValue();
        }
        return result.substring(result.indexOf("''") + "''".length(), result.length()).trim();
    }

But this downloads the full content of the response. I want to retrieve only the http headers without the content. A HEAD request seems not to work because then i get the status 501, not implemented. How can I do that?

回答1:

Instead of making a GET request, you might consider just making a HEAD request:

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.



回答2:

You might be able to use the Range header in your request to specify a range of bytes to include in the response entity. Possibly something like:

Range: bytes=0-0

If it does work, you should receive back a 206 Partial Content with the bytes specified in your Range header present in the response entity. However, I've not tried this, and it's also not guaranteed to work:

A server MAY ignore the Range header.