[iOS 多線程 & 網絡 - 2.6] - 使用POST上傳JSON數據 & 多值參數

A.上傳JSON
1.思路:
必須使用POST方法才能上傳大量JSON數據
設置請求頭:設置Content-Type
設置請求體,JSON實際至關於字典,能夠用NSDictionary
NSJSONSerialization把字典數據轉換成JSON二進制
 
 
2.實現
 1 //
 2 //  ViewController.m
 3 //  PostJsonDemo
 4 //
 5 //  Created by hellovoidworld on 15/1/28.
 6 //  Copyright (c) 2015年 hellovoidworld. All rights reserved.
 7 //
 8 
 9 #import "ViewController.h"
10 
11 @interface ViewController ()
12 - (IBAction)postJson;
13 
14 @end
15 
16 @implementation ViewController
17 
18 - (void)viewDidLoad {
19     [super viewDidLoad];
20     // Do any additional setup after loading the view, typically from a nib.
21 }
22 
23 - (IBAction)postJson {
24     // 1.建立請求
25     NSURL *url = [NSURL URLWithString:@"http://192.168.0.21:8080/MyTestServer/acceptJson"];
26     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
27     // 設置post發送
28     request.HTTPMethod = @"POST";
29    
30     // 2.設置請求頭
31     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
32    
33     // 3.設置請求體
34     NSDictionary *json = @{@"name":@"tom",
35                            @"age":@"21"};
36     request.HTTPBody = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
37    
38    
39     // 4.發送請求
40     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
41         NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]);
42     }];
43    
44 }
45 @end
 
 
B.多值參數
1.概念
一個參數名對應多個參數值
http://localhost:8080/MyTestServer/upload?type=aaa&type=bbb&type=ccc
這樣在服務器接收到的就是一個數組
相關文章
相關標籤/搜索