post發(fā)送JSON數(shù)據(jù)給服務(wù)器
觸發(fā)發(fā)送的方法
- 這次Demo是通過點(diǎn)擊屏幕觸發(fā)發(fā)送數(shù)據(jù)給服務(wù)器事件
- 前提需要開啟本地模擬服務(wù)器
- (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發(fā)送給服務(wù)器
// 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(@"請求數(shù)據(jù)失斃湮尽漱挎!");
return ;
}
// id recive = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
//服務(wù)器返回的時(shí)字符串
NSString *recive = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", recive);
}];
#pragma clang diagnostic pop
}
發(fā)送JSON字符串
- (NSData *)jsonString{
NSString *string = @"{\"name\":\"zhangsan\",\"age\":\"18\"}";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
return data;
}
發(fā)送字典給服務(wù)器
- (NSData *)dictionaryData{
NSDictionary *dict = @{
@"name":@"zhangsan",
@"age":@18
};
//通過序列化成data類型
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
return data;
}
發(fā)送數(shù)組給服務(wù)器
- (NSData *)arrayData{
NSArray *array = @[
@{@"zhangsan":@18},
@{@"lisi":@20}
];
NSData *data =[NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
return data;
}
發(fā)送oc對象給服務(wù)器
- 先將對象轉(zhuǎn)換為字典
- 通過系統(tǒng)提供的JSON解析類進(jìn)行序列化
- (NSData *)objectData{
RZPerson *person = [[RZPerson alloc]init];
person.name = @"zhangsan";
person.age = 20;
//先將對象轉(zhuǎn)換為字典類型
NSDictionary *dict = [person dictionaryWithValuesForKeys:@[@"name",@"age"]];
//將字典轉(zhuǎn)換為data類型
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
return data;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者