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

余生颓废 提交于 2019-12-01 00:49:44

问题


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.



来源:https://stackoverflow.com/questions/8852392/http-get-only-download-the-header-head-is-not-supported

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!