JSONデータをサーバに送信
4352 ワード
#pragma : JSON JSON
- (void)POSTJSON_01
{
NSString *jsonStr = @"{\"name\":\" \"}";
// JSON JSON
NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
[self postJsonWith:jsonData];
}
#pragma : JSON
- (void)POSTJSON_02
{
NSDictionary *dict = [NSDictionary dictionaryWithObject:@" " forKey:@"name"];
// JSON
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];
// 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];
}