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

iOS网络篇—发送json数据给服务器以及多值参数

2016-01-14 14:09 459 查看

    发送JSON给服务器

 
1 - 如何发送JSON给服务器
 
    A: 一定要使用POST请求。
 
        request.HTTPMethod = @"POST";
 
    B:设置请求头。
 
    1. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 
    2.设置JSON数据为请求体。
具体代码
<span style="font-size:14px;"> //URL
NSURL* url = [NSURL URLWithString:@"http://127.0.0.1:8080/Server/order"];
// 请求
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
// 超时
request.timeoutInterval = 5;
// 请求方式
request.HTTPMethod = @"POST";

// 设置请求体和参数
// 创建一个描述订单的JSON数据
NSDictionary* orderInfo = @{@"shop_id":@"12342",
@"shop_name":@"果冻",
@"user_id":@"hzdg111"};
// OC对象转JSON
NSData* json = [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];
// 设置请求头
request.HTTPBody = json;
// 设置请求头类型 (因为发送给服务器的参数类型已经不是普通数据,而是JSON)
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSURLSession* session = [NSURLSession sharedSession];
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// 错误判断
if (data==nil||error)return;
// 解析JSON
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString* resultErro = dic[@"error"];
if (resultErro)
{
NSLog(@"错误信息:%@",resultErro);
}else
{
NSLog(@"结果信息:%@",dic[@"success"]);
}
}];

[task resume];</span> B:多值传参
假设一个URL需要传递多个同样的参数并让服务器返回不同的数据,一般使用拼接方式
例:http://192.168.1.103:8080/MJServer/weather?place=广州&place=北京&place=上海
服务器的place是一个数组对象,所以多个参数不会把原来的覆盖
<span style="font-size:18px;color:#ff0000;"> NSURL* url = [NSURL URLWithString:@"http://127.0.0.1:8080/MJServer/weather"];
// 请求
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
// 超时
request.timeoutInterval = 5;
// 请求方式
request.HTTPMethod = @"POST";

// 设置请求体和多值参数
NSMutableString* param = [NSMutableString string];
[param appendString:@"place=beijing"];
[param appendString:@"&place=tianjing"];
[param appendString:@"&place=chuangzhou"];
// 设置请求头
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
// 发送请求
NSURLSession* session = [NSURLSession sharedSession];
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// 错误判断
if (data==nil||error)return;
// 解析JSON
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString* resultErro = dic[@"error"];
if (resultErro)
{
NSLog(@"错误信息:%@",resultErro);
}else
{
NSArray* weathers = dic[@"weathers"];
NSLog(@"结果信息:%@",weathers);
}
}];

[task resume];</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JSON GET ios 网络 数据