码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2016-06-06 10:26:52      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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

一、发送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开发网络篇—发送json数据给服务器以及多值参数

标签:

原文地址:http://www.cnblogs.com/yipingios/p/5562728.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!