3

The following code logs the correct JSON but in my web app that receives the request the body is empty:

    String body = '';

    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();

    req.setEndpoint('https://......herokuapp.com/....');
    req.setMethod('POST');

    JSONGenerator gen = JSON.createGenerator(true);    
    gen.writeStartObject();      
    gen.writeNumberField('Id', 2);
    gen.writeEndObject();    
    String jsonS = gen.getAsString();
    System.debug('json:' + jsonS);

    req.setBody(jsonS);

    req.setCompressed(true); // otherwise we hit a limit of 32000

    try {
        System.debug('req.getBody:' + req.getBody());

        res = http.send(req);
        body = res.getBody();
    } catch(System.CalloutException e) {
        System.debug('Callout error: '+ e);
        System.debug(res.toString());
    }

This results in the following, which is the JSON I expect:

15:11:20:003 USER_DEBUG [20]|DEBUG|json:{
15:11:20:000 USER_DEBUG   "Id" : 2
15:11:20:000 USER_DEBUG }
15:11:20:003 USER_DEBUG [27]|DEBUG|req.getBody:{
15:11:20:000 USER_DEBUG   "Id" : 2
15:11:20:000 USER_DEBUG }

In my web app:

console.log(`POST request, req.body: ${JSON.stringify(req.body)}`);

results in:

POST request, req.body: {}

Any ideas why the body is empty?

UPDATE: In the Web App, I use Express and the route looks like so:

app.post('/reset-pin', (req, res) => {
console.log(`POST request, req.body: ${JSON.stringify(req.body)}`);
3

Dave did some good sleuthing by testing his request in Postman and finding that it did arrive correctly in the web app.

So, my suggestion in a comment above was:

Not necessarily something wrong in SF, if you look at the request Postman is generating (click the "Code" link in the app), you'll see it generates some headers e.g. Content-Type. It could be that your app is dropping the body if no Content-Type is declared. Try to make your SF code do exactly the same as Postman regarding headers, then see where you are.

Which turned out to be the answer, so I'm posting is as-such.

3

Thanks to Aidan for his comment, I examined the headers generated from the successful Postman request and adding the following fixed the problem:

req.setHeader('Content-Type', 'application/json');
  • 1
    Glad it solved the problem for you. Bit of SFSE etiquette: it would be nice if you could up-vote my comment that solved your problem. Or what we sometimes do is ask the commenter to post as an answer and accept that. I'm not that desperate for points, but just FYI as it seems you're quite new here. – Aidan May 1 '18 at 15:58
  • 1
    @Aidan I'll do both! If you wish to write an answer I'll accept that. – Dave Chambers May 1 '18 at 15:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.