Sunday 19 June 2016

How to handle a 301 redirect response to my HTTP callout

While trying out https callounts we typically see response with Status=Moved Permanently, StatusCode=301. Below is the code sample which gives us error:
Http h = new Http();
HttpRequest req = new HttpRequest();
     
req.setHeader('Authorization', 'bearer ' + 'xxxxxxxxxx');
req.setEndpoint('https://www..com/v1.2/accounts');        
req.setMethod('GET');
req.setHeader('Content-Type', 'application/json; charset=UTF-8');
req.setTimeout(60*1000);
HttpResponse res = h.send(req);
String resString = res.getBody();
This errors generally occurs when target point we hit for, has permanently moved to a new location so in this case response should include this location. to fix this error we just need to get location out of first response and hit it again.So Finally code should be like below:

Http h = new Http();
HttpRequest req = new HttpRequest();
       
req.setHeader('Authorization', 'bearer ' + 'xxxxxxxxxx');
req.setEndpoint('https://www..com/v1.2/accounts');        
req.setMethod('GET');
req.setHeader('Content-Type', 'application/json; charset=UTF-8');
req.setTimeout(60*1000);
HttpResponse res = h.send(req);
String resString = res.getBody();
String loc = res.getHeader('Location'); // get location of the redirect
req = new HttpRequest();
req.setEndpoint(loc);
req.setMethod('GET');
req.setHeader('Authorization', 'bearer ' + 'xxxxxxxxxx');
        res = h.send(req);

Now it gives Status code 200 with Status "OK"