您的位置:首页 > 理论基础 > 计算机网络

IOS学习之 网络编程(8)--发送json数据给服务器以及多值参数

2015-11-30 15:20 609 查看
转载自 http://www.cnblogs.com/wendingding/p/3950132.html

一、发送JSON数据给服务器发送JSON数据给服务器的步骤:(1)一定要使用POST请求(2)设置请求头(3)设置JSON数据为请求体代码示例:
#import "YYViewController.h"
@interface YYViewController ()
@end
@implementation YYViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 1.创建请求
NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/order"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";

// 2.设置请求头
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

// 3.设置请求体
NSDictionary *json = @{
@"order_id" : @"123",
@"user_id" : @"789",
@"shop" : @"Toll"
};

//    NSData --> NSDictionary
// NSDictionary --> NSData
NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = data;

// 4.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%d", data.length);
}];
}
@end
二、多值参数多值参数:一个参数对应多个值。如下面的请求参数:http://192.168.1.103:8080/MJServer/weather?place=北京&place=河南&place=湖南服务器的place属性是一个数组。因此用同一个参数不会把服务器的值覆盖。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS 网络