Shashi Shirke
Shashi Shirke

Reputation: 93

how to use HEAD method of HTTPClient to get all headers

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

Upvotes: 3

Views: 10971

Answers (3)

Saket Mehta
Saket Mehta

Reputation: 2508

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

Upvotes: 1

douglaslps
douglaslps

Reputation: 8168

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

Upvotes: 2

Andrew
Andrew

Reputation: 7516

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.

Upvotes: 1

Related Questions