如何使用 post 方法发布字典和数组服务器
Posted
技术标签:
【中文标题】如何使用 post 方法发布字典和数组服务器【英文标题】:how to post dictionary and array server using post mathods 【发布时间】:2015-05-02 19:22:41 【问题描述】:如何发布 json 服务器我正在尝试添加字典和发布数据但没有收到写入响应
"类型":"一般", "noteText":["lineNo":"1","lineText":"患者入院"]
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSString *Str = @"general";
NSString *St2r = @"Yogesh";
NSString *Str1 = @"1";
NSMutableArray *tempArray = [[NSMutableArray alloc]init];
NSDictionary *tempDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
Str1, @"lineNo",
St2r, @"lineText",
nil];
[tempArray addObject:tempDictionary];
NSDictionary *tempDict = [[NSDictionary alloc]initWithObjectsAndKeys:tempArray,@"noteText", nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:tempDict options:0 error:&error];
//[请求设置HTTPBody:postData];
NSString *jsonRequest = [NSString stringWithFormat:@"\"type\":\"%@\"",Str]; // NSLog(@"Request: %@", jsonRequest);
NSURL *url7 = [NSURL URLWithString:@"URl"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url7];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPBody:postData];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
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];
在哪里?将其添加到 dataTaskWithRequest 的末尾。
我也对这些行感到困惑:[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
和 [request setHTTPBody: requestData];
你为什么使用 requestData? [request setHTTPBody:postData];
就够了,然后在请求中加上postData content-length:
你应该使用 AFNetworking 库:github.com/AFNetworking/AFNetworking
【参考方案1】:
也许考虑使用 AFNetworking?
您可以从here下载代码
使用以下代码作为对服务器的后调用示例。
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @@"foo": @"bar";
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
NSLog(@"JSON: %@", responseObject);
failure:^(AFHTTPRequestOperation *operation, NSError *error)
NSLog(@"Error: %@", error);
];
【讨论】:
以上是关于如何使用 post 方法发布字典和数组服务器的主要内容,如果未能解决你的问题,请参考以下文章
是否可以在 Afnetworking POST 方法中发布字典数组?
如何通过 Post 方法使用 JSON 模型将 JSON 字典作为参数传递?