0

We are facing some problems while authorization with twitter API: https://api.twitter.com/oauth2/token

Below is my code:

String keyencoded = EncodingUtil.urlEncode(consumerkey, 'UTF-8');
String secretkeyencoded = EncodingUtil.urlEncode(consumer secret key, 'UTF-8');

//Create Final Key String
String sFinal = keyencoded + ':' + secretkeyencoded;

//Convert to Blob
Blob headerValue = Blob.valueOf(sFinal);
//Build Request
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.twitter.com/oauth2/token');
req.setMethod('POST');

///Add Auth Header
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);

//You need to add this to the request - proved easy to miss in instructions...
req.setBody('grant_type=client_credentials');

//Make request
Http http = new Http();
HTTPResponse res = http.send(req);
String stoken;
//Parse JSON for Bearer Token
JSONParser parser = JSON.createParser(res.getBody());
while (parser.nextToken() != null) 
{
if (parser.getCurrentToken() == JSONToken.FIELD_NAME && parser.getText() == 'access_token')
{
parser.nextToken();
stoken = parser.getText();
}
}

HttpRequest req2 = new HttpRequest();
//I actually store the endpoint in the same custom setting and build dynamically, but for purposes of demo:
req2.setEndpoint('https://api.twitter.com/1.1/users/search.json?q=Pankaj&page=1&count=3');
req2.setMethod('GET');

//Call Bearer token Method
//Note - unless invalidated, I believe you can store this and keep using it indefinitely, but again, to demo concept
String authorizationHeader2 = 'Bearer ' + stoken;
req2.setHeader('Authorization', authorizationHeader2);

Http http2 = new Http();
HTTPResponse res2 = http2.send(req2);
String sBody = res2.getBody();
system.debug('===sBody==='+sBody);

We are able to get the token value, but while making the call out it is showing following message:

{"errors":[{"message":"Your credentials do not allow access to this resource","code":220}]}

Can someone suggest us anything on this front? Thanks in advance!

  • Did you try using curl to test out your request with the values hardcoded in there? – Phil B May 11 '15 at 13:35
0

Try adding Basic in the setHeader

setHeader('authorization','basic authorisationHeader');

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.