iOS中请求数据的方式有两种方式 GET、 POST
POST: 地址栏中不会有表单请求的参数; 参数数量和长度没有限制
GET: 将表单请求中的参数拼接到地址中进行传递; 参数数量和长度不能超过255字节
安全性: 请求数据用GET 提交大量表单数据用POST
URL 的正规语法: 协议:// 授权(域名)/ 资源路径(文件按路径)?参数列表
(date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213)
一、 iOS9 之前有GET同步、POST同步、代理异步、 Block异步 方式请求数据
#pragma mark ----- GET方式进行同步请求
#define GETURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#import "News.h"
#define POSTURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define POSTBODY @"date=20151129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
- (void)GetSyncAction {
// 网络请求
// 1、生成URL
NSURL *url = [NSURLURLWithString:GETURL];
// 2、创建请求对象,绑定URL
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
// 3、发送请求
NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:nil];
// NSLog(@"%@",data);
// json 解析
NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingAllowFragmentserror:nil];
// NSLog(@"%@",dic[@"news"]);
self.data = [NSMutableArrayarray];
NSArray *array = dic[@"news"];
for (NSDictionary *dicin array) {
News *news = [[Newsalloc] init];
[news setValuesForKeysWithDictionary:dic];
[self.dataaddObject:news];
}
for (News *newsin self.data) {
NSLog(@"%@ -- %@ -- %ld",news.title, news.NId, news.sequence);
}
}
#pragma mark ------ POST 方式进行同步请求
- (void)PostSyncAction {
// 生成创建URL对象
NSURL *url = [NSURLURLWithString:POSTURL];
// 创建request对象
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
// 与get方式的两个不同
// 设置httpMethod
[request setHTTPMethod:@"POST"];
// 设置httpBody ,即传递参数
NSData *data = [POSTBODYdataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
// 发送同步请求
NSData * dataRE = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:nil];
NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:dataRE options:NSJSONReadingAllowFragmentserror:nil];
self.data = [NSMutableArrayarray];
NSArray *arr = dic[@"news"];
for (NSDictionary *dictin arr) {
News *news = [[Newsalloc] init];
[news setValuesForKeysWithDictionary:dict];
[self.dataaddObject:news];
}
for (News *newsin self.data) {
NSLog(@"%@ -- %@ -- %ld",news.title, news.NId, news.sequence);
}
}
#pragma mark ---------- 使用Block方式实现异步请求
- (void)GETBlockAsyncAction {
// 1、创建URL
NSURL *url = [NSURLURLWithString:GETURL];
// 2、创建请求对象
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
// 3、发送异步请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *_Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingAllowFragmentserror:nil];
self.data = [NSMutableArrayarray];
NSArray *tempArray = dic[@"news"];
for (NSDictionary *dictin tempArray) {
News *news = [[Newsalloc] init];
[news setValuesForKeysWithDictionary:dict];
[self.dataaddObject:news];
}
for (News *newin self.data) {
NSLog(@"%@",new.title);
}
}];
}
#pragma mark --------GET 代理方式进行异步请求(引入<NSURLConnectionDataDelegate>)
- (void) GETDelegateAsyncAction {
// 1、创建URL对象
NSURL *url = [NSURLURLWithString:GETURL];
// 2、创建URLRequest对象
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
// 3、同步和异步的不同
[NSURLConnectionconnectionWithRequest:request delegate:self];
}
// 当收到服务器响应的时候
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// 初始化结果数组
self.data = [NSMutableArrayarray];
// 初始化缓冲水桶
self.tempData = [NSMutableDatadata];
}
// 接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// 将读取的部分数据拼接到水桶中
[self.tempDataappendData:data];
}
// 当所有的数据接收完毕的时候
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// 对水桶中的所有数据进行解析
NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:self.tempDataoptions:NSJSONReadingAllowFragmentserror:nil];
NSArray *array = dict[@"news"];
for (NSDictionary *dicin array) {
News *news = [[Newsalloc] init];
[news setValuesForKeysWithDictionary:dic];
[self.dataaddObject:news];
}
// 循环打印,输出
for (News *newsin self.data) {
NSLog(@"%@",news.title);
}
}
二、 iOS9 之后(网络编程方式):POST异步实现、 GET异步实现
#pragma mark ========= 使用iOS9的新方法进行post异步请求
- (IBAction)PostAction:(UIButton *)sender {
// 1、创建URL
NSURL *url = [NSURLURLWithString:POSTURL];
// 2、 创建请求对象
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
// 3、
NSData *bodyData = [POSTBODYdataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
#warning 新方法 的不同
// 4.1、 创建会话
NSURLSession *session = [NSURLSessionsharedSession];
// 4.2、创建数据请求任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {
NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingAllowFragmentserror:nil];
NSLog(@"%@", dict);
}];
// 4.3、启动任务
[task resume];
}
#pragma mark ========== 使用iOS9的新方法进行get异步请求
- (IBAction)GetAction:(UIButton *)sender {
// 1、创建URL
NSURL *url = [NSURLURLWithString:GETURL];
// 2、创建请求对象
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
#warning iOS9的不同
// 3、创建会话
NSURLSession *session = [NSURLSessionsharedSession];
// 4、创建任务
NSURLSessionDataTask *tast = [session dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {
NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingAllowFragmentserror:nil];
NSLog(@"%@",dict);
}];
// 5、开始任务
[tast resume];
}
三、 对新旧方法的两种封装, 在以后可以直接调用
旧方法(iOS9之前)
+ (void)solveDataWithUrl:(NSString *)stringUrl andHttpMethod:(NSString *)httpMethod andHttpBody:(NSString *)httpBody andRevokeBlock:(DataBlock)block {
NSURL *url = [NSURLURLWithString:stringUrl];
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
// 将所有的字母转换成大写
NSString *method = [httpMethod uppercaseString];
if ([@"POST"isEqualToString:method]) {
[request setHTTPMethod:httpMethod];
NSData *data = [httpBodydataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
} else if ([@"GET"isEqualToString:method]){
} else {
// NSLog(@"方法类型参数错误");
@throw [NSExceptionexceptionWithName:@"WJ Param Error"reason:@"方法类型参数错误"userInfo:nil];
return;
}
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *_Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
block(data);
}];
}
新方法(iOS9之后)
+ (void)SolveDataWithURL:(NSString *)URL HttpMethod:(NSString *)method HttpBody:(NSString *)body revokeBlock:(AnalyDataBlock)block {
NSURL *url = [NSURLURLWithString:URL];
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
NSString *httpMethod = [method uppercaseString];
if ([@"POST"isEqualToString:httpMethod]) {
[request setHTTPMethod:httpMethod];
NSData *data = [httpMethoddataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
} else if ([@"GET"isEqualToString:httpMethod]) {
} else {
@throw [NSExceptionexceptionWithName:@"WJ Param Error"reason:@"方法类型错误"userInfo:nil];
return;
}
NSURLSession *session = [NSURLSessionsharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {
block(data);
}];
[task resume];
}
下面对下载图片也进行了一下封装, 在请求数据之中调用该方法可以直接请求下来图片(需要刷新界面),也可以直接使用第三方的SDWebImage下载图片
+ (void)SessionDownloadWithUrl:(NSString *)stringUrl revokeBlock:(ImageSolveBlock)block {
NSURL *url = [NSURLURLWithString:stringUrl];
NSMutableURLRequest * request = [[NSMutableURLRequestalloc] initWithURL:url];
NSURLSession *session = [NSURLSessionsharedSession];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *_Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSData *imageData = [NSDatadataWithContentsOfURL:location];
UIImage *image = [UIImageimageWithData:imageData];
// 从子线程回到主线程进行界面更新
dispatch_async(dispatch_get_main_queue(), ^{
block(image);
});
}];
[task resume];
}