通过JSON API Objective-C发送POST请求

时间:2015-06-23 17:08:46

标签: ios objective-c json http post

我正在使用oAuth2,而我正试图找出将登录凭据发布到API并接收秘密,secret_id和令牌的最佳方式。

API的log_in部分的JSON格式如下所示:

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

我发送登录凭据的原因是:

 - (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]);
}

然后实际发送请求:

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

现在,在测试我的代码时,我会检查response方法中的connection:DidReceiveResponse变量。请求的状态是400.为什么我会收到此错误,是否需要进行其他设置?

1 个答案:

答案 0 :(得分:1)

您的sHTTPBody不是json格式。要将其作为json,您可以创建数据字典。然后使用json序列化将其转换为json。

根据您的数据准备词典:

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

将字典转换为Json数据:

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

最后使用json数据发送帖子请求:

[request setHTTPBody:postData];

这应该有效。请注意此代码中的语法和次要错误。我没有测试过。您可能需要稍微调整一下方法才能使用此代码。