Geethanadh Geethanadh - 11 days ago 6
Java Question

Fetching a custom header of a request (Java HTTP)

I am trying to implement a get request of a webpage through Java (using Apache HTTP API).

The webpage is sending an custom header value in the get request which i am not able to simulate in the java code.

When i open a webpage it sends a request header "AO-7DEABF" with some auto-generated value (value is consistent for a login session), and the web page would not respond unless i send the same value through my java code.

How do i fetch the actual value from a web-page from my java code, so that i can send it along with my request.

Sample Code im am using

import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;

public class Test{
public static void main(String args[]){
HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
CookieStore cookieStore = new BasicCookieStore();
Executor executor = Executor.newInstance(client).use(cookieStore);

String url = "www.sampleurl.com";
Request req = Request.Get(url);
String response = executor.execute(request).returnContent().asString();
}
}


Request Header

GET /rest/zephyr/latest/zql/executeSearch/?zqlQuery=&offset=20&maxRecords=0&expand=executionStatus&_=1444386966596 HTTP/1.1
Host: jira.devops.mnscorp.net
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
AO-7DEABF: Vwl8V0kdk7Xvyq9BFivbLpbSdpZ2tFjy182i1qYBju0o0KyWAPh9chbJvt9GRGvvf98RK8u1GHaclCm8FBEhbA==
Content-Type: application/json
Referer: https://<myclientjira>/secure/enav/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: wb48617274=C9B5D1A8; seraph.rememberme.cookie=24122%3A41d5dae1cd459348abecfb0ca5feee6766fd0ac0; JSESSIONID=1428066D5584823DFD572189A2456540; atlassian.xsrf.token=BSMP-3NDP-M3AB-8R70|98ba98938704a930babccb4a5912c01b762d9220|lin; wb48617274=90986387

Answer

you can take the header details in the response as below.

//get all headers       
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
    System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue());
}

//get header by 'key'
String server = response.getFirstHeader("xxxx").getValue();