以下是我从ObjectiveCloud获取访问令牌的Objective-c代码:
- (void) authoriseSoundcloud {
NSString *apiUrl = @"https://api.soundcloud.com/oauth2/token";
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[ NSURL URLWithString:apiUrl]];
NSString * params = [NSString stringWithFormat:@"client_id=%@&client_secret=%@grant_type=password&username=%@&password=%@",client,secretKey,fldUsername.text,fldPassword.text ];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *defaultSession = [NSURLSession sharedSession];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text);
}
}];
[dataTask resume];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text);
}
}];
[dataTask resume];
但是,我总是得到结果401- }
。
但是,该客户端ID与那些请求完美配合,不需要授权,我已多次检查,我的客户端ID和密码是正确的。
由于iOS没有太多样本在HTTP帖子体中使用这些参数,我假设我的参数列表可能不正确。来自Soundcloud工程师的任何想法?
答案 0 :(得分:2)
只是一个拼写错误,只需添加"&"介于" client_secret =%@"和" grant_type",像这样:
NSString * params = [NSString stringWithFormat:@"client_id=%@&client_secret=%@&grant_type=password&username=%@&password=%@",client,secretKey,fldUsername.text,fldPassword.text ];
像魅力一样工作:)