给服务器发送JSON数据
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSDictionary *product = @{@"product":@"葵花宝典",@"price":@"99.9"};
NSDictionary *product1 = @{@"product":@"金瓶梅",@"price":@"199.9"};
NSArray *products = @[product,product1];
if(![NSJSONSerialization isValidJSONObject:products]) {
NSLog(@"无效的json对象");
return;
}
NSData *data = [NSJSONSerialization dataWithJSONObject:products options:0 error:NULL];
[self postJson:data];
}
- (void)postJson:(NSData *)data {
NSURL *url = [NSURL URLWithString:@"http://localhost/post/postjson.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = data;
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(@"%@---%@",response,[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
}