how to use HEAD method of HTTPClient to get all headers

 ̄綄美尐妖づ 提交于 2019-12-23 17:22:56

问题


I have to use HEAD method of HttpClient to get the header field and to check the "last-modified" date of server file.
I am not able to get that, if you know how to get the header field then please reply. How to get the "last-modified" header into the String object for the comparison.

Here is my code:

HttpClient client = new DefaultHttpClient();
//HttpGet get = new HttpGet(url);
HttpHead method = new HttpHead(url);
HttpResponse response= client.execute(method);

Header[] s = response.getAllHeaders();

System.out.println("THe header from the httpclient:");
for(int i=0; i < s.length; i++){
    Header hd = s[i];
    System.out.println("Header Name: "+hd.getName()
                        +"       "+" Header Value: "+ hd.getValue());
}

回答1:


On httpClient 4.5 you would use:

final HttpHead headMethod = new HttpHead(fileUri);
final Header header = headMethod.getFirstHeader("last-modified");
final String lastModified = header.getValue();



回答2:


From the HttpClient documentation

HeadMethod head = new HeadMethod("http://jakarta.apache.org");

// Excecute the method here with your HttpClient

Header[] headers = head.getResponseHeaders();
String lastModified = head.getResponseHeader("last-modified").getValue();

You'll need to add your own error handling.




回答3:


It would be best to use something like this:

CloseableHttpClient client = HttpClientBuilder.create().build();
HttpHead head = new HttpHead(url);
String lastModified;
try {
    CloseableHttpResponse response = client.execute(head);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 200) {
        Header header = headMethod.getFirstHeader("last-modified");
        lastModified = header.getValue();
    }
} catch (IOException ignored) {
}


来源:https://stackoverflow.com/questions/7819975/how-to-use-head-method-of-httpclient-to-get-all-headers

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