You need to sign in to do that
Don't have an account?
HttpRequest Apex call returns binary data
We have an Apex method calling out a REST API Get method, which suddently started responding with binary data instead of JSON. We have not made any changes to the code in the REST API, and using tools like Postman, browser request or JS-fetch returns the appropriate JSON response.
Has anyone experience an issue like this? Other REST APIs do not have the same issue, but our prod, sandbox and scratch orgs all return the same corrupted response.
Here is a sample of the basic call we have in Apex:
@AuraEnabled
public static String getEventById(String eventId) {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://RESTURI/' + eventId);
request.setMethod('GET');
request.setHeader('Content-Type', 'application/json');
HttpResponse response = http.send(request);
// Parse the JSON response
if (response.getStatusCode() != 200) {
System.debug('The status code returned was not expected: ' + response.getStatusCode() + ' ' + response.getStatus());
return null;
}
return response.getBody();
}
We are getting a status code 200, but the body of the response is just a lot of random binary data.
The Content-Type header is used to inform the Server what YOU are sending. In your case you're telling the Server that you're sending JSON data, and not something else.
The Accept header is used to tell the Server what kind of response you would be happy with. I think you should use it, to tell the server that you want JSON output, and not binary junk.
Add this line:
request.setHeader('Accept', 'application/json');
Please mark this comment as best answer if it's help you.