如何使用HTTPClient的HEAD方法获取所有头文件

时间:2011-10-19 10:37:03

标签: java header http-headers httpclient head

我必须使用HEAD HttpClient方法获取标题字段并检查服务器文件的“最后修改日期”。
我无法得到它,如果您知道如何获得标题字段,请回复。 如何将“last-modified”标头放入String对象中进行比较。

这是我的代码:

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());
}

3 个答案:

答案 0 :(得分:2)

在httpClient 4.5上,您将使用:

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

答案 1 :(得分:1)

来自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();

您需要添加自己的错误处理。

答案 2 :(得分:1)

最好使用这样的东西:

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) {
}