1.GET请求
self.dataArray = [NSMutableArray array];
NSURL *url = [NSURL URLWithString:HTTPURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"请求失败");
}else{
NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
for (NSDictionary *dic in diction) {
NEWS *news = [[NEWS alloc] init];
[news setValuesForKeysWithDictionary:dic];
[self.dataArray addObject:news];
}
}
}];
[dataTask resume];
2.POST请求
- (void)loadData{
NSString *string = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL * url = [NSURL URLWithString:string];
NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
request.HTTPMethod = @"POST";
NSString *dataString = @"date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = data;
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"请求失败");
}else {
NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
for (NSDictionary *dic in diction[@"news"]) {
NEWS *news = [[NEWS alloc] init];
[news setValuesForKeysWithDictionary:dic];
[self.dataArray addObject:news];
}
NSLog(@"%@",self.dataArray);
}
}];
[dataTask resume];
}
注意:
在解析数据的时候,创建news对象的时候,必须要for循环的内部创建,否则,数组中的数据将都一样.
网友评论