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;
    }

转载须注明出处:http://www.jianshu.com/p/384805833374

猜你喜欢

转载自blog.csdn.net/sinat_34194127/article/details/51585003