[SalesForce] HTTP Callout Error

I have the below code trying to make a HTTP callout from a APEX class. The response I get back is

System.HttpResponse[Status=Moved Temporarily, StatusCode=302]

However if I use the same URL to make the callout form a REST client in firefox I get the desired JSON body back. Can you please advise what I am doing wrong in the below code in salesforce ?

     HttpRequest req = new HttpRequest();

     req.setEndpoint('http://host-name/sap/opu/odata/sap/TEST;mo/Carriers?$format=json');
     req.setMethod('GET');
     String username = 'XXXXXXXXX';
     String password = 'YYYYYYYYYY';

     Blob headerValue = Blob.valueOf(username + ':' + password);
     String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
     System.debug( 'authorizationHeader : ' + authorizationHeader );
     req.setHeader('Authorization', authorizationHeader);


     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());

The return message that I get back from the Apache server has the new url in it. It is the same url as above but with the https. I am still confused with the original call though. Why does normal browser or another rest client show me the response with status code 200 and salesforce shows status code 302

Best Answer

You are doing nothing wrong. The HTTP request object provided by Salesforce does not handle 302 redirects like your browser does.

You can try handling redirects by running the callout again on the redirected site, as shown in this answer, or you can use a tool to find out what the ultimate endpoint is, like redirect detective.

As long as you are able to hit this ultimate end-point site in your browser, you should be able to query it from the Salesforce HTTP object. Make your HTTP object query it, and it should all work.