如何发布json服务器我正在尝试添加字典和发布数据但没有得到写入响应
{“type”:“general”,“noteText”:[{“lineNo”:“1”,“lineText”:“patient admited”}]}
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];
// [request setHTTPBody: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);
}
}];
1 回答
考虑使用AFNetworking吗?
你可以从here下载代码
使用以下代码作为对服务器的后调用的示例 .