发送JSON数据到服务器

  • 方案一 : 把JSON格式的字符串序列化成JSON的二进制
#pragma 方案一 : 把JSON格式的字符串序列化成JSON的二进制
- (void)POSTJSON_01
{
    NSString *jsonStr = @"{\"name\":\"大发明家\"}";

    // 把JSON格式的字符串序列化成JSON的二进制
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    [self postJsonWith:jsonData];
}
  • 方案二 : 把字典序列化成JSON格式的二进制
#pragma 方案二 : 把字典序列化成JSON格式的二进制
- (void)POSTJSON_02
{
    NSDictionary *dict = [NSDictionary dictionaryWithObject:@"亚索" forKey:@"name"];

    // 把字典序列化成JSON格式的二进制
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
    [self postJsonWith:jsonData];
}
  • 方案三 : 把数组序列化成JSON格式的二进制
#pragma 方案三 : 把数组序列化成JSON格式的二进制
- (void)POSTJSON_03
{
    NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"牛头" forKey:@"name"];
    NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"石头人" forKey:@"name"];
    NSArray *arr = @[dict1,dict2];

    // 把数组序列化成JSON格式的二进制
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:0 error:NULL];
    [self postJsonWith:jsonData];
}

发送json数据到服务器的主方法,传入json数据的二进制

#pragma 发送json数据到服务器的主方法,传入json数据的二进制
- (void)postJsonWith:(NSData *)jsonData
{
    // URL
    NSURL *URL = [NSURL URLWithString:@"http://localhost/php/upload/postjson.php"];
    // 请求
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:URL];
    // 设置请求方法
    requestM.HTTPMethod = @"POST";
    // 设置请求体
    requestM.HTTPBody = jsonData;

    // 发送请求
    [[[NSURLSession sharedSession] dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 处理响应
        if (error == nil && data != nil) {

            // 反序列化
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);

        } else {
            NSLog(@"%@",error);
        }
    }] resume];
}

你可能感兴趣的:(发送JSON数据到服务器)