[iOS 多线程 & 网络 - 2.6] - 使用POST上传JSON数据 & 多值参数

时间:2022-10-28 08:30:08
A.上传JSON
1.思路:
必须使用POST方法才能上传大量JSON数据
设置请求头:设置Content-Type
设置请求体,JSON实际相当于字典,可以用NSDictionary
NSJSONSerialization把字典数据转换成JSON二进制
 
 
2.实现
 //
// ViewController.m
// PostJsonDemo
//
// Created by hellovoidworld on 15/1/28.
// Copyright (c) 2015年 hellovoidworld. All rights reserved.
// #import "ViewController.h" @interface ViewController ()
- (IBAction)postJson; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
} - (IBAction)postJson {
// 1.创建请求
NSURL *url = [NSURL URLWithString:@"http://192.168.0.21:8080/MyTestServer/acceptJson"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 设置post发送
request.HTTPMethod = @"POST"; // 2.设置请求头
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; // 3.设置请求体
NSDictionary *json = @{@"name":@"tom",
@"age":@""};
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil]; // 4.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]);
}]; }
@end
 
 
B.多值参数
1.概念
一个参数名对应多个参数值
http://localhost:8080/MyTestServer/upload?type=aaa&type=bbb&type=ccc
这样在服务器接收到的就是一个数组