HttpGet adding header
20,188
Solution 1
Use the setHeader() method on the HttpGet object like follows.
httpGet.setHeader("If-Modified-Since","11/26/2012");
I used this JavaDoc as a reference.
Solution 2
Use the setHeader() method on the HttpGet object like follows for the first one
httpGet.setHeader("If-Modified-Since","11/26/2012");
and then use addHeader() method on the HttpGet object like as follows for the second header.
httpGet.addHeader("If-Expires-On","11/26/2014");
Author by
Ken
Updated on September 05, 2020Comments
-
Ken over 3 years
I am creating a httpClient and I want to add certain header to my HttpGet request
My current code produces the following request.GET /folder/index.html HTTP/1.0
Host: localhost:4444
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.2.1 (java 1.5)What I want is to add another header (If-Modified-Since) in that request .
How can I do it?
Thank you :)public String httpGet(String s) { String url = s; StringBuilder body = new StringBuilder(); httpclient = new DefaultHttpClient(); // create new httpClient HttpGet httpGet = new HttpGet(url); // create new httpGet object try { response = httpclient.execute(httpGet); // execute httpGet StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_OK) { // System.out.println(statusLine); body.append(statusLine + "\n"); HttpEntity e = response.getEntity(); String entity = EntityUtils.toString(e); body.append(entity); } else { body.append(statusLine + "\n"); // System.out.println(statusLine); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpGet.releaseConnection(); // stop connection } return body.toString(); // return the String }
-
Darpan about 10 yearscan we add ultiple setHeaders on same httpGet object? I want to add more than one header.