【轉】iOS開發網路篇—發送json資料給伺服器以及多值參數

來源:互聯網
上載者:User

標籤:

原文: 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資料給伺服器以及多值參數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.