I have configured Moodle in all ways to receive API calls, and am able to make successful API calls from Postman, the address bar of any web browser, etc., but am having an issue translating it into working in Apex. Through testing, I believe I have narrowed things down to one question that if answered will solve the problem:
I have enabled "http://[mymoodleinstance].com" as a Remote Site in Salesforce.
If I try to make a callout to the api endpoint for my instance, "http://[mymoodleinstance].com/webservice/rest/server.php" from the normal address bar in any web-browser window (or from Postman, etc.), I will at least get the error message (letting me know an attempt to associate with my Moodle instance has been initiated and recognized by the system as an attempt) that says "invalid token," XML that is a response from the Moodle system.
If I try to access that same endpoint using Apex code, "http://[mymoodleinstance].com/webservice/rest/server.php", my Apex code being this:
Http H = new Http(); HttpRequest Req = new HttpRequest(); Req.setEndpoint('http://[mymoodleinstance].com/webservice/rest/server.php'); Req.setMethod('POST'); HttpResponse Res = H.send(Req); system.debug(Res.getBody());
I get a debug message that says "Bad Request, 400", all of that stuff. Here is the exact message if that helps (the exact tags that come back with the response as well):
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>400 Bad Request</title> </head><body> <h1>Bad Request</h1> <p>Your browser sent a request that this server could not understand.<br /> </p> <p>Additionally, a 400 Bad Request error was encountered while trying to use an ErrorDocument to handle the request.</p> </body></html>
Any thoughts? Why would something work in Postman and as a normal, address-bar request and not in Apex? I've tried:
- Including and removing the headers that are generated with Postman requests, but then the request still work in the address bar, which has no headers
- Variations of html encoding, using EncodingUtil