1

I'm having trouble getting a POST request to go trough using the Execute Anonymous window. The endpoint is exactly the same in my postman and it goes trough with no issues, but keeps returning a 400 when sent from Salesforce.

I HAVE added 'https://graph.facebook.com' to my Remote Site Settings enter image description here

And here is the code on the Execute Anonymous..

HttpRequest req = new HttpRequest();
req.setMethod('POST');                                    
//Seting HttpRequest Method
req.setHeader('content-type', 'application/json');       
//Seting HttpRequest header properties
req.setHeader('Content-Length', '2000');
req.setEndpoint('https://graph.facebook.com/v15.0/xxxxxxxxx/messages?recipient={id:xxxxxxxxxxxx}&message={text:"HELLO, HOW ARE YOU"}&messaging_type=MESSAGE_TAG&tag=ACCOUNT_UPDATE&access_token=xxxxxxxxxxxxxxxxxx');
Http http = new Http();
try{
    HTTPResponse res = http.send(req);                 
    //Executing web service call
    System.debug('STATUS:' + res.getStatus());
    System.debug('STATUS_CODE:' + res.getStatusCode());
}
catch(System.CalloutException e){
    //Exception handling goes here..
    system.debug(e);
}

Which is returning:

enter image description here

But is successful in Postman: enter image description here

4
  • 1
    Might be safer if you commented out at least part of that access token. Nov 19, 2022 at 17:54
  • 1
    Also, I'd remove the content length header unless you are certain that it is exactly 2000 characters long. Also, you are specifying this as a post, but you are not putting anything in the POST body. Are you sure this should be a post? Nov 19, 2022 at 17:59
  • Also, while HTTP headers are case insensitive... who knows what facebook is doing. Try making it Content-Type. Finally back to the POST thing, try formatting the way it does it in this page: developers.facebook.com/docs/messenger-platform/… Nov 19, 2022 at 18:16
  • @CasparHarmer weird thing... in the debug log, the access_token is being truncated... ie: System.HttpRequest[Endpoint=https://graph.facebook.com/v15.0/106622318855859/messages?recipient={id:5420438071372198}&message={text:"random text here"}&messaging_type=MESSAGE_TAG&tag=ACCOUNT_UPDATE&access_token=EAAHU2qak6aMBAC2Hp8Pk4NsBp5FSui0fCkRysRm5rFIzmMj6ntVefhBddnrZBfsTHci5IdZBH9k3bDbnI64VOjyMbKrI**TRUNCATEDHERE** so I ended up shortening the message to just 'hi' and it ended up posting....
    – potato46
    Nov 19, 2022 at 21:30

1 Answer 1

0

via: https://stackoverflow.com/a/36284027/19789973 I found out it is the whitespace in the text string causing the issue. I Replaced this using '%20' and the POST was successful! For example: text:"random%20text%20here"

1
  • 1
    You should use urlEncode method from EncodingUtil Class, it will take care of this.
    – Saroj Bera
    Nov 20, 2022 at 17:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .