How to access httpClient response headers in javascript?

Not applicable

After doing the following , I wanted to access headers in the response recieved from httpClient. How can I do that ?

var newRequest = new Request(tempUrl,"POST",headers,"{}");
var pitRequest = httpClient.send(newRequest);
pitRequest.waitForComplete();
if( pitRequest.isSuccess() ) { ... }	
Solved Solved
1 8 32.5K
1 ACCEPTED SOLUTION

Great Question @AlayVakil ,

Here you go,

var r = httpClient.get("http://mocktarget.apigee.net/json");
// set the pending request into a context variable
context.setVariable('pendingResponse', r); 


var r = context.getVariable('pendingResponse');
if (r) {
    // retrieve the pending request from the context variable
    r.waitForComplete();
    if (r.isSuccess()) {
        print(r.getResponse().headers['Content-Length']);
    }
}

I am not sure how to retrieve all response headers names though. If you know the header, You can retrieve using above code. Hope it helps.

View solution in original post

8 REPLIES 8

Great Question @AlayVakil ,

Here you go,

var r = httpClient.get("http://mocktarget.apigee.net/json");
// set the pending request into a context variable
context.setVariable('pendingResponse', r); 


var r = context.getVariable('pendingResponse');
if (r) {
    // retrieve the pending request from the context variable
    r.waitForComplete();
    if (r.isSuccess()) {
        print(r.getResponse().headers['Content-Length']);
    }
}

I am not sure how to retrieve all response headers names though. If you know the header, You can retrieve using above code. Hope it helps.

sabthar
Participant I

Just Adding to Anil's response, If you need to know all the headers in the response then use below lines

if (r) { // retrieve the pending request from the context variable 
    r.waitForComplete();
    if (r.isSuccess()) {
        print("
            Content Length => " , r.getResponse().headers['Content-Length']);print("
            All headers == > ",  JSON.stringify(r.getResponse().headers) );for (var j in r.getResponse().headers) { print( j, 
            "==> ", r.getResponse().headers[j]);
    }
}

@Sabthar , Awesome, +1, Thank you for sharing the code & it works as expected. I have tried "r.getResponse().headers" without JSON.stringify. Just wondering, How did you came to know about above solution ?

Thanks @Anil Sagar for your prompt responses. On the above code snippet, Since it is an object, so converted to (JSON) string while printing...

@docs team, @Floyd Jones , @sgilson Can we update this information in this page here & here ? Thank you !

I can take care of it @Anil Sagar -- thanks!

Awesome, Thank you for quick reply @wwitman

@Anil Sagar, @Sabthar -- Based on your code I created a new sample called iterate-headers in our api-platform-samples site on GitHub. I also linked to it from the Apigee docs you suggested above. -- Will