登录成功,我获得了代码和状态。 然后,我正在尝试通过以下链接中的节目中链接的POST请求获取访问令牌:Exchange Authorization Code for an Access Token
这是我的代码(Objective-c):
-(void)requestForAccessToken:(NSString*)authorizationCode
{
NSString *grantType = @"authorization_code";
NSString *redirect = [redirectURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
NSString *postParams = [NSString stringWithFormat:@"grant_type=%@&code=%@&redirect_uri=%@&client_id=%@&client_secret=%@", grantType, authorizationCode, redirect, [ELConfig getLinkedinClientId], [ELConfig getLinkedinClientSecret]];
NSURL *url = [NSURL URLWithString:accessTokenEndPoint];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
NSData *data = [postParams dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = data;
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSURLSessionDataTask *task = [[NSURLSession sharedSession]
dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError* err;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&err];
NSLog(@"dict: %@", json);
NSString *accessToken = [json objectForKey:@"access_token"];
NSLog(@"accessToken: %@", accessToken);
if (accessToken != nil) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"additionalDtaKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
dispatch_async(dispatch_get_main_queue(), ^{
[self popViewController];
});
}
}];
}
[task resume];
-(void)requestForAccessToken:(NSString*)authorizationCode
{
NSString *grantType = @"authorization_code";
NSString *redirect = [redirectURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
NSString *postParams = [NSString stringWithFormat:@"grant_type=%@&code=%@&redirect_uri=%@&client_id=%@&client_secret=%@", grantType, authorizationCode, redirect, [ELConfig getLinkedinClientId], [ELConfig getLinkedinClientSecret]];
NSURL *url = [NSURL URLWithString:accessTokenEndPoint];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
NSData *data = [postParams dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = data;
[request addValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"Content-Type"];
NSURLSessionDataTask *task = [[NSURLSession sharedSession]
dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError* err;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&err];
NSLog(@"dict: %@", json);
NSString *accessToken = [json objectForKey:@"access_token"];
NSLog(@"accessToken: %@", accessToken);
if (accessToken != nil) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"additionalDtaKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
dispatch_async(dispatch_get_main_queue(), ^{
[self popViewController];
});
}
}];
[task resume];
}
和斯威夫特:
func requestForAccessToken(authorizationCode: String) {
let grantType = "authorization_code"
let redirectURL = "https://com.test.linkedin.oauth/oauth".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())!
// Set the POST parameters.
var postParams = "grant_type=\(grantType)&"
postParams += "code=\(authorizationCode)&"
postParams += "redirect_uri=\(redirectURL)&"
postParams += "client_id=\(linkedInKey)&"
postParams += "client_secret=\(linkedInSecret)"
// Convert the POST parameters into a NSData object.
let postData = postParams.dataUsingEncoding(NSUTF8StringEncoding)
// Initialize a mutable URL request object using the access token endpoint URL string.
let request = NSMutableURLRequest(URL: NSURL(string: accessTokenEndPoint)!)
// Indicate that we're about to make a POST request.
request.HTTPMethod = "POST"
// Set the HTTP body using the postData object created above.
request.HTTPBody = postData
// Add the required HTTP header field.
request.addValue("application/x-www-form-urlencoded;", forHTTPHeaderField: "Content-Type")
// Initialize a NSURLSession object.
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
// Make the request.
let task: NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
// Get the HTTP status code of the request.
let statusCode = (response as! NSHTTPURLResponse).statusCode
if statusCode == 200 {
// Convert the received JSON data into a dictionary.
do {
let dataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
let accessToken = dataDictionary["access_token"] as! String
NSUserDefaults.standardUserDefaults().setObject(accessToken, forKey: "LIAccessToken")
NSUserDefaults.standardUserDefaults().synchronize()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})
}
catch {
print("Could not convert JSON data into a dictionary.")
}
}
}
task.resume()
}
我总是遇到以下错误:
{
error = "missing_parameter";
"error_description" = "A required parameter \"client_id\" is missing";
}