user3663218
user3663218

Reputation: 49

Sending POST Request through JSON API Objective-C

I'm using oAuth2 and I'm trying to figure out the best way to POST login credentials to the API and receive the secret, secret_id, and token in return.

The JSON formatting for the log_in portion of the API looks like:

POST auth/log_in HTTP/1.1
Host: hostSite.com
Content-Type: application/JSON
Authorization: Basic Base64(client_id:client_secret)
{
    "username": "[email protected]"
    "password": "Purpl3H0rs3Oc3an"
    "grant_type": "password"
    "request_refresh": "true"
}

What I have for the sending the login credentials is:

 - (BOOL) loginUser
{
NSString *  sUserName = [m_jsonDict valueForKey:@"username"],
         *  sPassword = [m_jsonDict valueForKey:@"password"],
         *  sJSON = [NSString   stringWithFormat:@"userName: %@\npassword: %@\n",
                                              sUserName, sPassword];

return ([self POSTUsingCommand:@"login" andData:sJSON]);
}

Then to actually send the request:

     (BOOL) POSTUsingCommand : (NSString *) sCommand
         andData                : (NSString *) sData
{
    BOOL                    ret = NO;
    NSString            *   url = [NSString stringWithFormat:CONST_PATH, NSLocalizedString(sCommand, nil)]; 
    //hostSite.com/auth/log_in

    NSString            *   sHTTPBody = sData;
    NSMutableURLRequest *   request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                          timeoutInterval:15.0];

#if defined(DEBUG)
    NSLog(@"--- POSTUsingCommand:\n%@\n", sHTTPBody);
#endif

    // build out the post command

    [request setHTTPMethod:@"POST"];
    [request setValue:@"Application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"Application/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPBody:[sHTTPBody dataUsingEncoding:NSUTF8StringEncoding]];

    if ([NSURLConnection connectionWithRequest:request
                                      delegate:self] == nil)
    {
#if defined(DEBUG)
        NSLog(@"There was a problem with initWithRequest:delegate\n");
#endif
    }
    else
    {
        ret = YES;
    }

    return (ret);
}

Now when testing my code I inspect the response variable in the connection:DidReceiveResponse method. The status of the request is a 400. Why do I get this error is there additional setup that needs to be done?

Upvotes: 0

Views: 843

Answers (1)

ntsh
ntsh

Reputation: 759

Your sHTTPBody is not in json format. To get this as json, you can create a dictionary of your data. Then convert it into json using json serialization.

Prepare Dictionary from your data:

NSMutableDictionary *dataDict = [NSMutableDictionary new];
[dataDict setObject:sUserName forKey:@"username"];
[dataDict setObject:sPassword forKey:@"password"];
// And so on ...

Convert dictionary into Json data:

NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict 
                                                   options:0
                                                     error:&error];

Finally send a post request with json data:

[request setHTTPBody:postData];

This should work. Take care of the syntax and minor errors in this code. I have not tested it. You might have to tweak your methods a bit to use this code.

Upvotes: 1

Related Questions