POST JSON (字典 自定义类转为JSON上传)

/// POST JSON 的主方法 主要设置  Content-Type 为  application/json 剩下就是将 类转为JSON 格式二进制数

- (void)postJSON:(NSData *)data {

    // 1. url

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/postjson.php"];

    

    // 2. request

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    

    // 2.1 httpMethod

    request.HTTPMethod = @"POST";

    // 2.2 设置 content-type,有些服务器在接收数据的时候,会做数据类型的校验

    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    // 2.3 设置数据

    request.HTTPBody = data;

    

    // 3. connection

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

    }];

}

 

/// POST 字典 组成的数组 或单独的字典

- (void)postDict {

    NSDictionary *dict1 = @{@"productId": @123, @"productName": @"Mac pro"};

    NSDictionary *dict2 = @{@"productId": @001, @"productName": @"iPhone 7"};

    

    NSArray *array = @[dict1, dict2];

    

    // 序列化,将数据发送给服务器之前,将字典/数组 -> 二进制数据

    // 数据解析 - 反序列化,将服务器返回的二进制数据转换成字典或者模型

    NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];

    

    [self postJSON:data];

}

 

// KVC   将类的属性转为字典,再将字典序列化

- (void)postPerson {

  // 参数:传入对象数组转换成字典

    id obj = [self.person dictionaryWithValuesForKeys:@[@"name", @"age", @"title", @"height"]];

    

    // 顶级节点,是数组或者字典

    if (![NSJSONSerialization isValidJSONObject:obj]) {

        NSLog(@"数据格式无效");

        return;

    }

    NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:0 error:NULL];

    

    [self postJSON:data];

}

posted @ 2015-06-10 01:55  风中一场梦  阅读(872)  评论(0编辑  收藏  举报