post发送JSON数据(字符串、数组、字典、自定义对象)给服务器

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;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,099评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,267评论 4 61
  • JSON JSON和XML都是需要解析的 JSON是一种轻量级的数据格式,一般用于数据交互服务器返回给客户端的数据...
    JonesCxy阅读 1,895评论 2 10
  • 漫步在弯曲的小路上, 听雨水滑落的声音—— 淅淅沥沥, 演奏着一曲 专属思念的蓝色旋律。 回忆伴着雨水...
    木叶丶飘阅读 135评论 0 2
  • 斯蒂芬·沃尔夫勒姆 http://www.guokr.com/article/439770/ 0306 薛定谔的猫...
    白头山大将军阅读 1,211评论 0 50