You need to sign in to do that
Don't have an account?
Jayesh Sonawane
System.HttpResponse[Status=Moved Permanently, StatusCode=301]
hi everyone,
I am calling an API with Authtoken in header :
I am calling an API with Authtoken in header :
String resp = 'response : '; HttpRequest req = new HttpRequest(); JSONGenerator gen = JSON.createGenerator(false); JSONGenerator gen = JSON.createGenerator(false); String url = 'http://api.xxxxx.com/xx/xxx/xxx'; req.setEndpoint(url); String reqJSON; gen.writeStartObject(); gen.writeStringField ('transaction_id', txnID); gen.writeEndObject(); // Get the JSON string. reqJSON = gen.getAsString(); req.setBody(reqJSON); req.setEndpoint (url); req.setHeader('Authorization', 'Token xxxxxxxxxxxxxxxxxxxxxxxx'); req.setMethod ('GET'); req.setHeader('Content-Type', 'application/json'); req.setHeader('Accept', 'application/json'); req.setBody(reqJSON); req.setTimeout(60000); // Get response httpResponse res = new http().send(req); resp = resp + ' : ' + res.getBody() + ' - ' + res.toString(); ApexPages.addMessage(new ApexPages.Message( ApexPages.Severity.info,resp));but the output i am able to see is this
response : : - System.HttpResponse[Status=Moved Permanently, StatusCode=301]what may be the issue here ,
- I have checked the API , its working fine on Postman and other platform.
- I have added the api url on Remote Sites.
thanks for your quick rply btw. i don't think this is an issue regarding request Method.
Hi,
It has been 2 years since the original post, but when I face this problem I came to this page but didn't find answer hopefully this helps someone else out in the same situation.
Whenever URL redicting to another URl we will get 3xx status codes. Https to http or vice versa. In my case it was redicteing from https to http.
Browsers will automatically handles these redirections and gives response. For apex we need to handle in the code.
So when you get this status code you need to make a second request using the value you find in the 'Location' header of the first response.
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://us18.api.instance.com/');
request.setMethod('GET');
HttpResponse response = http.send(request);
System.debug('Scode-->'+response.getStatusCode());
If(response.getStatusCode() == 301 || response.getStatusCode() == 302)
{
request.setEndpoint(response.getHeader('Location'));
response = new Http().send(request);
}