三步走:
1.使用POST请求
2.设置请求头
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
3.设置JSON数据为请求体
1 // 2 // ViewController.m 3 // IOS_0130_发送JSON给服务器 4 // 5 // Created by ma c on 16/1/30. 6 // Copyright © 2016年 博文科技. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 #import "MBProgressHUD+MJ.h" 11 12 @interface ViewController () 13 14 @end 15 16 @implementation ViewController 17 18 - (void)viewDidLoad { 19 [super viewDidLoad]; 20 self.view.backgroundColor = [UIColor cyanColor]; 21 // Do any additional setup after loading the view, typically from a nib. 22 } 23 24 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 25 { 26 //1.URL 27 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/order"]; 28 //2.请求 29 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 30 //3.请求方法 31 request.HTTPMethod = @"POST"; 32 //4.设置请求体 33 //创建一个描述订单信息的JSON数据 34 NSDictionary *dict = @{ 35 @"shop_id" : @"123456", 36 @"shop_name" : @"bowen", 37 @"user_id" : @"2012110606" 38 }; 39 NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil]; 40 request.HTTPBody = json; 41 42 //5.设置请求头:这次请求体的数据不再是参数,而是JSON数据 value:MIMEType 43 [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 44 45 //6.发送请求 46 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { 47 if (data == nil || connectionError) return; 48 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; 49 NSString *error = dict[@"error"]; 50 if (error) { 51 [MBProgressHUD showError:error]; 52 } 53 else{ 54 NSString *success = dict[@"success"]; 55 [MBProgressHUD showSuccess:success]; 56 } 57 }]; 58 } 59 @end
原文:http://www.cnblogs.com/oc-bowen/p/5172205.html