- 方案一 : 把JSON格式的字符串序列化成JSON的二进制
#pragma 方案一 : 把JSON格式的字符串序列化成JSON的二进制
- (void)POSTJSON_01
{
NSString *jsonStr = @"{\"name\":\"大发明家\"}";
NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
[self postJsonWith:jsonData];
}
#pragma 方案二 : 把字典序列化成JSON格式的二进制
- (void)POSTJSON_02
{
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"亚索" forKey:@"name"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
[self postJsonWith:jsonData];
}
#pragma 方案三 : 把数组序列化成JSON格式的二进制
- (void)POSTJSON_03
{
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"牛头" forKey:@"name"];
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"石头人" forKey:@"name"];
NSArray *arr = @[dict1,dict2];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:0 error:NULL];
[self postJsonWith:jsonData];
}
发送json数据到服务器的主方法,传入json数据的二进制
#pragma 发送json数据到服务器的主方法,传入json数据的二进制
- (void)postJsonWith:(NSData *)jsonData
{
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];
}