iOS開發網絡篇—發送json數據給服務器以及多值參數


iOS開發網絡篇—發送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)viewDidLoad
10 {
11     [super viewDidLoad];
12 }
13 
14 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
15 {
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 --> NSDictionary
32     // NSDictionary --> NSData
33     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屬性是一個數組。因此用同一個參數不會把服務器的值覆蓋。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM