【发布时间】: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