function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
prakash_sfdcprakash_sfdc 

Unable to post comment with line breaks on Chatter FeedItem using Chatter REST API from Apex

I am trying to post a simple text comment to FeedItem. The comment has line breaks.

Following is my code:
 
String comment = 'Test1\r\n\r\nTest2';

String access_token = AuthController.getJIRAOAuthToken();

String authVal = 'OAuth '+access_token;
HttpRequest req = new HttpRequest();
String endpoint = system.label.JIRA_OAuth_SFDC_REST_API_Endpoint+'/services/data/v35.0/chatter/feed-elements/';


System.debug(endpoint); 
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-Type','application/json; charset=UTF-8');

req.setHeader('Authorization', authVal);




req.setBody('{"body":{"messageSegments":[{"type":"Text","text":"'+comment+'"}]},"feedElementType":"FeedItem","subjectId":"a3gm0000000066S"}');


Http http = new Http();
//System.debug(req);
HTTPResponse res = http.send(req);
System.debug('**'+res);

I am getting below response.
System.HttpResponse[Status=Bad Request, StatusCode=400]

If I am trying the same code without "\r\n" then it works perfectly fine. Any suggestions please ?

I tried replacing "\r\n" with " " as per the rich text feed item https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/quickreference_post_feed_element_rich_text.htm but even that didn't help. The comment is posted along with " " in text.
Arun KumarArun Kumar
Hi Try to make Json String
{
   "body":{
      "messageSegments":[
         {
             "text" : "First line of text.",
             "type" : "Text"
         },         
         {
            "text" : "Second line of text.",
            "type" : "Text"
         }         
      ]
   },
   "subjectId":"me",
   "feedElementType":"FeedItem"
}

 like below:
prakash_sfdcprakash_sfdc
@Arun: Actually this won't solve my issue. I can't split every line break into different message segments.
Arun KumarArun Kumar
Hi,

Why you can't . you can simple right down the logic for creating this Json.

OR i will lokk for another solution.

Thanks,
Arun
matt.ian.thomasmatt.ian.thomas
Try 
'Test1 \r\n Test2`

Notice the spaces.
prakash_sfdcprakash_sfdc
@Arun: Yes I can but that won't be a good solution. There should be some way to escape or parse linebreaks. For now I am adding a paragraph message segment for a single line break and a " " text message segment for multiple line breaks. It's working now. 

@Matt: Sorry, it still gives the error. It looks like Chatter REST API doesn't support "\r\n". I may be wrong. But as per their documentation, we have to split the formatting into multiple message segments.

Looking for some good solution :(
George BTGeorge BT
String br = '<p></p>';

Then insert br wherever you need a line break.