This is pretty basic. Based on what I've read, this should work. I have a more complex version of this as well.
The To parameter listed below is a List of strings. From and Body are strings.
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.testdomain.com/batchemail');
request.setHeader('Authorization', 'Bearer ' + token);
request.setMethod('POST');
request.setHeader('Accept', '*/*');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
// Set the body as a JSON object
request.setBody('{"To": ["[email protected]"]}');
request.setBody('{"From": "[email protected]"}');
request.setBody('{"Body": "Test message"}');
HttpResponse response = http.send(request);
Here is an example of the JSON that the API accepts.
{
"to": ["[email protected]"],
"from": "[email protected]",
"body": "Test message"
}
The endpoint has been added in Remote Site Settings.
Any idea why this isn't working? Any help is much appreciated. Thanks!
UPDATE 1 (this works)
request.setBody('{"To": ["[email protected]"], "From": "[email protected]", "Body": "Test message." }');
UPDATE 2 (this works too)
JSONGenerator gen = JSON.createGenerator(true);
// Write data to the JSON string.
gen.writeStartObject();
gen.writeObjectField('to', emailList);
gen.writeStringField('from', '[email protected]');
gen.writeStringField('body', message);
gen.writeEndObject();
// Get the JSON string.
String pretty = gen.getAsString();
request.setBody(pretty);
Update 3 (this also works)
Gareth Jordan's Solution works as well.
For the first part, call setBody
once, your 3 calls to setBody
are just overwriting each other.
for the json generator part, you are double encoding, the variable pretty
contains the valid generated json, no need to call json.serialize
it.