I've got NullPointerException trying to analyze the value of content type header returned in HttpResponse object.
As it turns out, the case of the header name was different (i.e. 'content-type', but not 'Content-Type'), that's why HttpResponse object returns null instead of actual value.
I'm really confused cause according to http specification header names are case-insensitive.
So I've created a test mock and below is a piece of code to reproduce the issue:
HttpRequest request = new HttpRequest();
request.setEndpoint('http://demo8399479.mockable.io/testHeaderCase');
request.setMethod('GET');
HttpResponse response = new Http().send(request);
System.debug('Get header content-type: ' + response.getHeader('content-type'));
System.debug('Get header Content-Type: ' + response.getHeader('Content-Type'));
And here is debug output:
20:59:12:131 USER_DEBUG [9]|DEBUG|Get header Content-Type: application/json; charset=UTF-8
20:59:12:131 USER_DEBUG [8]|DEBUG|Get header content-type: null
So, what's than the right way to fetch header by name ? Am I doing something wrong ? Why is it case-sensitive in apex ?
Thanks in advance for throwing daylight on this mystery.
Best Answer
Summer '15 Apex Reference (Page 1865):
You should use
<Map>.keySet()
and then compare key value using<String>.equalsIgnoreCase(string)