2

I am beginner to REST APIs. I had a REST api used to login into some third party application. When used from Postman extension of Chrome it works well. However throws some generic error when used from Salesforce execute anonymous:

Httprequest request = new HttpRequest();
Http http = new Http();
request.setMethod('POST');
request.setEndpoint('http://someendpoint.com/service');
request.setTimeout(120000); 
String jsonString='{"login":"serviceusername","password":"passwordtologin","clientname":"101","clientappid":"202","clientappkey":"303"}';   
request.setBody(jsonString);          
System.debug('====='+request.getbody());     
//Making call to external REST API
HttpResponse response = http.send(request);  
System.debug('====='+response.getbody());

The only thing that I followed before using this api was including endpoint in remote site setting.I keep getting a generic response error saying invalid appkey/clientname. The reason I am saying its generic is because error remains same even when I use invalid username password. Am I missing something ?

Postman Screenshot: enter image description here

  • 2
    whats the error? – Mohith Shrivastava May 21 '16 at 20:15
  • Invalid client id/app key in response body. That means the request didn't hit in proper format, as all parameter values were correct. They worked when used from Postman. – Mukesh Verma May 21 '16 at 20:24
  • Could you screenshot postman parameters ,you can remove username and password and keep some dummy strings – Mohith Shrivastava May 21 '16 at 20:25
  • 1
    So clearly you are sending form data via POSTMAN and JSON data via SFDC which is causing issue .Try sending JSON data via postman – Mohith Shrivastava May 21 '16 at 20:38
  • 1
    can you set header as application/json and posting JSON to your external url via POSTMAN ?Sending via JSON from POSTMAN – Mohith Shrivastava May 21 '16 at 20:54
7

I would use the generate code button in postman, select the cUrl type. Take a look at the headers it generates on the working Postman version (the parameters with the -H) and add them to your apex using the setHeader method. Something like:

http.setHeader('content-type','application/Json');
  • Thank you JimRae. I was missing setting content-type header in my code. After setting content-type header to application/Json , things worked successfully. – Mukesh Verma May 22 '16 at 5:19

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.