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.

3
  • Is your res.getBody() also returning null? Commented Oct 13, 2016 at 18:36
  • res.getBody()=={"error":"invalid_grant","error_description":"authentication failure"} Commented Oct 13, 2016 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. Commented Oct 14, 2016 at 15:14

1 Answer 1

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());

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .