1

I want to pass json as request header in rest api request call using POST method.

Json :- { "comment" : "Check out developer.linkedin.com!", "visibility" : { "code" : "anyone" } }

     PageReference p = new PageReference(LINKEDIN_SHAREPOST+LINKEDIN_ACCESSTOKEN+'&format=json');
     p.getParameters().put('{"comment":"Check out developer.linkedin.com!","visibility":{"code": "anyone"}}'); 
     String body = p.getURL();
     body = body.subStringAfter('?');
     HttpRequest req = new HttpRequest();
     req.setEndpoint(LINKEDIN_SHAREPOST);
     req.setMethod('POST');
     req.setCompressed(false);
     req.setHeader('HOST','www.linkedin.com');

Its giving me error. How to do this ?

1

You can use this by Creating classes as below :

public class linkedinpostshare_API 
{
public String comment='';
public Content content{get;set;}
public Visibility visibility{get;set;}
public class Content 
{
    public String title='';
    public String description='';
    public String submitted_url='';
    public String submitted_image_url='';        
}
public class Visibility 
{
    public String code='';
} 

}

assign the class properties and make Rest API POST Call As below.

 linkedinpostshare_API objlinkedinpostshare_API = new linkedinpostshare_API();         
     linkedinpostshare_API.Visibility objVisibility = new linkedinpostshare_API.Visibility();

     objVisibility.code='anyone';
     objlinkedinpostshare_API.comment=post;         
     objlinkedinpostshare_API.visibility=objVisibility;       

     String jsonBody = json.serialize(objlinkedinpostshare_API);        
     HttpRequest req = new HttpRequest();
     req.setEndpoint(LINKEDIN_SHAREPOST+token+'&format=json');
     req.setMethod('POST');
     req.setCompressed(false);
     req.setHeader('HOST','www.linkedin.com');
     req.setHeader('Encoding','iso-8859-1'); 
     req.setHeader('Content-Type', LINKEDIN_REQUEST_CONTENTTYPE);
     req.setHeader('x-li-format', 'json');         
     req.setTimeout(120000);//max timeout
      if(jsonBody != null )
         { 
             req.setBody(jsonBody);
             req.setHeader('Content-length',string.valueOf(jsonBody.length()));
         }
         HttpResponse res = new http().send(req);

       return res.getBody();

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.