我在通过Objective-C POST请求检索Lyft API的访问令牌时遇到了问题(我对POST请求很新)。 Lyft API文档将此作为示例请求进行了详细说明:
POST /oauth/token HTTP/1.1
Authorization: Basic base64(client_id:client_secret)
Content-Type: application/json;charset=UTF-8
{
"grant_type": "authorization_code",
"code": "<authorization_code>"
}
这是他们文档中的卷曲请求:
curl -X POST -H "Content-Type: application/json" \
--user "<client_id>:<client_secret>" \
-d '{"grant_type": "authorization_code", "code": "<authorization_code>"}' \
'https://api.lyft.com/oauth/token'
我如何在Objective-C中实现这一点?这是我现在的代码:
NSString *post = [[NSString alloc] initWithFormat: @"{grant_type: client_credentials, scope: public}"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSURL *lyftURL = [NSURL URLWithString: @"https://api.lyft.com/oauth/token"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:lyftURL];
[req setHTTPMethod:@"POST"];
[req addValue: @"application/json" forHTTPHeaderField: @"Content-Type"];
NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"UK83N70T5vBx", @"6Fw8SnbIXPJ9v9_OnBRczvP1DIXqD1H2"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64Encoding]];
[req setValue:authValue forHTTPHeaderField:@"Authorization"];
[req setHTTPBody: postData];
[NSURLConnection sendAsynchronousRequest: req queue: [NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError)
NSLog(@"ERROR");
else {
NSLog(@"DATA: %@", data);
NSError* error;
NSDictionary* lyftJSON = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(@"JSON: %@", lyftJSON);
}
}];
我收到以下错误:'无法找到或解析grant_type,您是否正确设置了Content-Type标头?'
以下是Lyft文档的链接:[https://developer.lyft.com/docs/authentication][1]
如果我能够知道我的问题在我的代码中的位置,那就太棒了。