post发送JSON数据(字符串、数组、字典、自定义对象)给服务器
来源:互联网 发布:淘宝店铺粉丝最多 编辑:程序博客网 时间:2024/05/21 10:36
post发送JSON数据(字符串、数组、字典、自定义对象)给服务器
触发发送的方法
- 这次Demo是通过点击屏幕触发发送数据给服务器事件
- 前提需要开启本地模拟服务器
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/post/postjson.php"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15]; request.HTTPMethod = @"POST"; //选择不同类型的data发送给服务器// request.HTTPBody = [self jsonString];// request.HTTPBody = [self dictionaryData];// request.HTTPBody = [self arrayData]; request.HTTPBody = [self objectData];#pragma clang diagnostic push#pragma clang diagnostic ignored "-Wdeprecated-declarations" [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { if (data == nil || connectionError != nil) { NSLog(@"请求数据失败!"); return ; }// id recive = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];//服务器返回的时字符串 NSString *recive = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", recive); }];#pragma clang diagnostic pop}
发送JSON字符串
- (NSData *)jsonString{NSString *string = @"{\"name\":\"zhangsan\",\"age\":\"18\"}";NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];return data;}
发送字典给服务器
- (NSData *)dictionaryData{NSDictionary *dict = @{ @"name":@"zhangsan", @"age":@18 };//通过序列化成data类型NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];return data;}
发送数组给服务器
- (NSData *)arrayData{NSArray *array = @[ @{@"zhangsan":@18}, @{@"lisi":@20} ];NSData *data =[NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];return data;}
发送oc对象给服务器
- 先讲对象转换为字典
- 通过系统提供的JSON解析类进行序列化
- (NSData *)objectData{ RZPerson *person = [[RZPerson alloc]init]; person.name = @"zhangsan"; person.age = 20; //先将对象转换为字典类型 NSDictionary *dict = [person dictionaryWithValuesForKeys:@[@"name",@"age"]]; //将字典转换为data类型 NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL]; return data; }
转载须注明出处:http://www.jianshu.com/p/384805833374
0 0
- post发送JSON数据(字符串、数组、字典、自定义对象)给服务器
- iOS开发-post请求向服务器发送json格式数据(数组或字典)
- iOS开发-post请求向服务器发送json格式数据(数组或字典)
- 发送json字符串给服务器
- 给服务器发送JSON数据
- 发送JSON数据给服务器
- 给服务器发送JSON数据
- 发送json数据给服务器
- 用AFN发送字符串形式的Json数据给服务器
- iOS开发-给服务器发送JSON数据
- swift3.0 发送json数据给服务器
- 使用curl库,以post方式向服务器发送json/字符串数据
- OkHttp之post请求发送给服务器json
- php7游戏端以post发送json数据给php
- golang post发送application/json数据到服务器
- c++ HTTP POST请求 向服务器发送json数据
- libcurl HTTP POST请求向服务器发送json数据
- HttpURLconnection使用POST方式提交JSON数据给服务器
- dataset总结
- 链接和库
- ListView的点击事件应用
- Batch Normalization导读
- 自定义拖拽IndicatorView
- post发送JSON数据(字符串、数组、字典、自定义对象)给服务器
- 手把手教你开发基于深度学习的人脸识别【考勤/签到】系统
- EditTexts实现图文混排
- Tomcat7.0源码分析——启动与停止服务原理
- netlink socket编程实例
- 串口通信中的float型数据的处理
- git
- linux下实现一个进度条
- C语言大纲——C语言的概述