如何在Salesforce中调用具有OAuth2.0的外部API

时间:2019-07-17 05:53:01

标签: rest oauth-2.0 salesforce

检查了Auth.providers并创建了具有oauth详细信息的命名凭证,但是auth管理员处于待处理状态。

我在下面尝试了其他选项

我在哪里出错,因为我无法拨打成功电话并打印响应?

共享类为FILENAME {

的公共
private String consumerKey = 'Consumer_KEY'; 
private String consumerSecret = 'Consumer_secret '; 
public String generatedToken {set; get;}

public String errorMessage {set; get;}


public void getTokenFromTwitter() {
    try{
        String consumerKeyEncoded = EncodingUtil.urlEncode(consumerKey, 'UTF-8');
        String consumerSecretEncoded = EncodingUtil.urlEncode(consumerSecret, 'UTF-8');
        String ketTokenCombined = consumerKeyEncoded + ':' + consumerSecretEncoded;
        HttpRequest objReq = new HttpRequest();
        objReq.setEndpoint('https://MYSITE/oauth2/token');
        objReq.setMethod('POST');
        String authHeadParam = 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(ketTokenCombined));
        objReq.setHeader('Authorization', authHeadParam);
        objReq.setBody('grant_type=client_credentials');
        Http objHttp = new Http();
        HTTPResponse objRes = objHttp.send(objReq);
        System.debug('----response :'+ objRes.getBody());
        JSONParser objParse = JSON.createParser(objRes.getBody());
        while (objParse.nextToken() != null) 
        {
            if (objParse.getCurrentToken() == JSONToken.FIELD_NAME && objParse.getText() == 'access_token')
            {
                objParse.nextToken();
                generatedToken = objParse.getText();
            }
        }
     }
     catch(Exception ex)
     {  errorMessage = ex.getMessage();
        System.debug('Exception :' + ex.getMessage());
     }
}

public void getTweetTimelines() {
    getTokenFromTwitter(); // Generate new access token before calling bellow API
    if(generatedToken == null ) {
        twitterTimelineResponse = 'Error while generating token, so unable to get messages. Check your debug log.';
        return;
    }
    try{
        HttpRequest objReq = new HttpRequest();
        objReq.setEndpoint('https://MYSITE/PATH');
        objReq.setMethod('GET');
        objReq.setHeader('Authorization', 'Bearer ' + generatedToken);
        Http objHttp = new Http();
        HTTPResponse objRes = objHttp.send(objReq);
        twitterTimelineResponse = objRes.getBody();
        if(String.isBlank(twitterTimelineResponse)){
            twitterTimelineResponse = objRes.toString();
        }
        System.debug('----response :'+ TimelineResponse);
        // Put Your JSON Parsing Logic Here for twitterTimelineResponse
     }
     catch(Exception ex)
     {  errorMessage = ex.getMessage();
        System.debug('Exception :' + ex.getMessage());
     }
}  

}

0 个答案:

没有答案