POST Request in Objective-C with Lyft API Access T

2019-09-14 19:46发布

问题:

I'm encountering an issue in retrieving my access token for the Lyft API via an Objective-C POST request (I'm pretty new to POST requests). The Lyft API documentation details this as an example request:

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>"
}

This is the curl request from their documentation:

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'

How would I implement this in Objective-C? This is my code right now:

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

        }
    }];

I'm getting the following error: 'Could not find or parse grant_type, did you set the Content-Type header correctly?'

Here is the link to the Lyft documentation: [https://developer.lyft.com/docs/authentication][1]

It would be great if I could know where my issue lies in my code.