3

我必须使用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());
}
4

3 回答 3

2

在 httpClient 4.5 上,您将使用:

final HttpHead headMethod = new HttpHead(fileUri);
final Header header = headMethod.getFirstHeader("last-modified");
final String lastModified = header.getValue();
于 2015-07-21T10:32:19.387 回答
1

来自 HttpClient文档

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

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

于 2011-10-19T10:48:13.917 回答
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) {
}
于 2016-12-14T06:19:09.460 回答