在iOS中的post请求中无法将json字符串作为param发送?

时间:2015-07-16 08:00:37

标签: ios objective-c iphone json ipad

我试图在post请求中将Json字符串作为param发送,但我无法做到这一点。我有一系列电话号码,我正在生成一个json字符串,后面是代码

int i=0;
NSMutableArray *contacts = [[NSMutableArray alloc] init];
for (i=0; i<[all_contacts count]; i++)
{
    [contacts addObject:@{@"phone" : [all_contacts objectAtIndex:i]}];
}


NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contacts options:0 error:&error];
if (!jsonData)
{
    //error here
}
else
{
     JsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
     NSLog(@"json string is %@",JsonString);
}

现在我正在转换为使用post请求发送到服务器的nsdata,但我无法做到这一点。

//append base url with main url
    NSString* urlString=[BASE_URL stringByAppendingString:ADD_CONTACTS];

    // the server url to which the image (or the media) is uploaded. Use your server url here
    NSURL* requestURL = [NSURL URLWithString:urlString];

    // Create the request.
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];

    // Specify that it will be a POST request
    request.HTTPMethod = @"POST";

    // This is how we set header fields
    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:api_key forHTTPHeaderField:@"Authorization"];


    // Convert your data and set your request's HTTPBody property

    NSDictionary *_params = [NSDictionary dictionaryWithObjectsAndKeys:
                          JsonString, @"contacts",
                          nil];
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:_params options:0 error:nil];

    request.HTTPBody = jsonData;

    NSString *string = [NSString stringWithUTF8String:[jsonData bytes]];
    NSLog(@"ns local data is%@", string);


    // Create url connection and fire request
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

1 个答案:

答案 0 :(得分:0)

你似乎有点过分思考它。您在contacts中有一系列词典。为什么不简单地执行以下操作?

NSError *error = nil;
NSDictionary *_params = @{@"contacts": contacts};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:_params options:0 error:&error];
request.HTTPBody = jsonData;