標籤:
原文: http://www.cnblogs.com/wendingding/p/3950132.html
一、發送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
二、多值參數
多值參數:一個參數對應多個值。
如下面的請求參數:
http://192.168.1.103:8080/MJServer/weather?place=北京&place=河南&place=湖南
伺服器的place屬性是一個數組。因此用同一個參數不會把伺服器的值覆蓋。
【轉】iOS開發網路篇—發送json資料給伺服器以及多值參數