【问题标题】:how to pass a dictionary using NSURLSession in post method?如何在 post 方法中使用 NSURLSession 传递字典?
【发布时间】:2014-08-03 00:09:40
【问题描述】:

我不知道如何通过 POST 使用 NSURLSession 将字典中的值传递到服务器。请帮我解决这个问题。

我的字典包含联系信息(仅限姓名和电话号码),其中键是人名,值是他们的电话号码。

我有使用 nsurl 连接的示例代码 - 如何将其转换为使用 NSURLSession

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://holla.com/login"]];

request.HTTPMethod = @"POST"; [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"212333333",@"ABCD",@"6544345345",@"NMHG", nil];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
request.HTTPBody = jsonData;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

【问题讨论】:

标签: ios nsurlsession


【解决方案1】:

我通过以下方法解决了这个问题:

NSError *error;

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL * url = [NSURL URLWithString:[ NSString stringWithFormat:@"http://xxxx.com/login/save_contact"]];;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];

NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:@"212333333",@"ABCD",@"6544345345",@"NMHG",
                         nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];


NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)

{       
    
    if(error == nil)
    {
        NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
        NSLog(@"Data = %@",text);
    }
    
}];

[postDataTask resume];

【讨论】:

    猜你喜欢
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多