注:GET请求,请求参数放在URL上;POST请求,请求参数建议用JSON格式放在请求体里面
一、发送JSON数据给服务器
发送JSON数据给服务器的步骤:
(1)一定要使用POST请求
(2)设置请求头
(3)设置JSON数据为请求体
代码示例:
1 #import "YYViewController.h" 2 3 @interface YYViewController () 4 5 @end 6 7 @implementation YYViewController 8 9 - (void)viewDidLoad10 {11 [super viewDidLoad];12 }13 14 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event15 {16 // 1.创建请求17 NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/order"];18 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];19 request.HTTPMethod = @"POST";20 21 // 2.设置请求头22 [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];23 24 // 3.设置请求体25 NSDictionary *json = @{26 @"order_id" : @"123",27 @"user_id" : @"789",28 @"shop" : @"Toll"29 };30 31 // NSData --> NSDictionary32 // NSDictionary --> NSData33 NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];34 request.HTTPBody = data;35 36 // 4.发送请求37 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {38 NSLog(@"%d", data.length);39 }];40 }41 42 @end
二、多值参数
多值参数:一个参数对应多个值。
如下面的请求参数:
服务器的place属性是一个数组。因此用同一个参数不会把服务器的值覆盖。