1

I am trying to connect org using rest api. I am getting error:[Status=Bad Request, StatusCode=400].I am not getting access token back Here is my Code:

<apex:page controller="SendWaveUsingRESTAPI">
<apex:form >
<apex:pageBlock >
<apex:actionFunction action="{!ReturnAccessToken}" name="wavescript" immediate="true" Id="WaveId"/>
<input id="clickMe" type="button" value="Connect" onclick="wavescript();"/>
</apex:pageBlock>
</apex:form>
</apex:page>

class:

public class SendWaveUsingRESTAPI {
  private final String clientId = 'XXXX';
   private final String clientSecret = 'XXXXXX';
   private final String username = 'XXXX';
   private final String password = 'XXXXX';
  public class deserializeResponse
   {
      public String id;
      public String access_token;
   }
  public void ReturnAccessToken()
   {
      String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
     Http h = new Http();
      HttpRequest req = new HttpRequest();
      req.setBody(reqbody);
      req.setMethod('POST');
      req.setEndpoint('https://XXXXXXX.my.salesforce.com/services/oauth2/token');
      HttpResponse res = h.send(req);
     deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
     system.debug('@@@@access_token@@'+resp1 );
   }
}

in the resp1 it is coming as null.

  • Is your res.getBody() also returning null? – battery.cord Oct 13 '16 at 18:36
  • res.getBody()=={"error":"invalid_grant","error_description":"authentication failure"} – Vidhyasagaran Muralidharan Oct 13 '16 at 18:48
  • Thanks metadaddy,tushar. Because of IP restriction in the org when I connect I am getting the authentication failure.I Modified Outh2.0 policies to to relax Ip restriction got the response. – Vidhyasagaran Muralidharan Oct 14 '16 at 15:14
1

Most likely problem is non-URL safe characters in the username and/or password - you should URL-encode those parameters. Here is working code I wrote a few years ago:

HttpRequest req = new HttpRequest(); 

req.setMethod('POST');
req.setEndpoint(loginUri+'/services/oauth2/token');
req.setBody('grant_type=password' +
    '&client_id=' + clientId +
    '&client_secret=' + clientSecret +
    '&username=' + EncodingUtil.urlEncode(username, 'UTF-8') +
    '&password=' + EncodingUtil.urlEncode(password, 'UTF-8'));

Http http = new Http();

HTTPResponse res = http.send(req);

System.debug('BODY: '+res.getBody());
System.debug('STATUS:'+res.getStatus());
System.debug('STATUS_CODE:'+res.getStatusCode());
| improve this answer | |

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.