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

///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...

//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')
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:

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

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
    Commented May 11, 2015 at 13:35

1 Answer 1


Try adding Basic in the setHeader

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

You must log in to answer this question.

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