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

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

一、发送JSON数据给服务器

发送JSON数据给服务器的步骤:

(1)一定要使用POST请求

(2)设置请求头

(3)设置JSON数据为请求体

代码示例:

复制代码
 1 #import "YYViewController.h"
 2 
 3 @interface YYViewController ()
 4 
 5 @end
 6 
 7 @implementation YYViewController
 8 
 9 - (void)viewDidLoad
10 {
11     [super viewDidLoad];
12 }
13 
14 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
15 {
16     // 1.创建请求
17     NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/order"];
18     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
19     request.HTTPMethod = @"POST";
20     
21     // 2.设置请求头
22     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
23     
24     // 3.设置请求体
25     NSDictionary *json = @{
26                            @"order_id" : @"123",
27                            @"user_id" : @"789",
28                            @"shop" : @"Toll"
29                            };
30     
31 //    NSData --> NSDictionary
32     // NSDictionary --> NSData
33     NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
34     request.HTTPBody = data;
35     
36     // 4.发送请求
37     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
38         NSLog(@"%d", data.length);
39     }];
40 }
41 
42 @end
复制代码

 

二、多值参数

多值参数:一个参数对应多个值。

如下面的请求参数:

http://192.168.1.103:8080/MJServer/weather?place=北京&place=河南&place=湖南

服务器的place属性是一个数组。因此用同一个参数不会把服务器的值覆盖。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值