GET,POST的同步和异步所有中代码方法
Posted 钎探穗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GET,POST的同步和异步所有中代码方法相关的知识,希望对你有一定的参考价值。
#pragma GET同步:
//开发中 不推荐使用同步网络请求
- (IBAction)getT:(id)sender {//通过storyboard关联得到的方法
//地址字符串
NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
//统一资源定位符(URL)
NSURL *url = [NSURL URLWithString:urlString];
//第一个参数:统一资源定位符(URL)
//第二个参数:缓存策略
//第三个参数:超时时间
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:60.0f];
//NSURLConnection在ios 9.0之后不推荐使用
// 第一个参数: NSURLRequest 类型的对象
// 第二个参数: 存储的是一些网络请求的信息,一般为 nil(包体)
// 第三个参数: 错误信息
NSData *data = [NSURLConnection sendSynchronousRequest: request returningResponse:nil error:nil];
NSLog( @"data=====%@", data);
//解析数据
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
NSLog(@"dic===%@", dic);
}
/*
NSURLRequestUseProtocolCachePolicy
:基础缓存策略
* NSURLRequestReloadIgnoringLocalCacheData
:忽略本地缓存
* NSURLRequestReloadIgnoringLocalAndRemoteCacheData
:忽略本地缓存,无论本地是否有缓存,都从网络下载
NSURLRequestReloadIgnoringCacheData=NSURLRequestReloadIgnoringLocalCacheData,
:如果本地缓存有效,则不下载,无效则去下载
NSURLRequestReturnCacheDataElseLoad
:优先的使用本地缓存,如果本地没有缓存,则去下载
* NSURLRequestReturnCacheDataDontLoad
:从不下载,只使用本地缓存,如果没有则请求失败.多用于离线环境
** NSURLRequestReloadRevalidatingCacheData
:验证本地数据和网络数据是否相同,如果不同,则去下载,如果相同,则使用本地缓存
*/
#pragma POST同步:
- (IBAction)postT:(id)sender {
NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlrequest = [NSMutableURLRequest requestWithURL:url];
//创建一个字符串
NSString *dataString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
//把这个字符串转换成NSData类型的对象
NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
//设置请求方式 方式为大写 如:POST GET
//GET请求可以不设置,但是POST请求必须设置
[urlrequest setHTTPMethod:@"POST"];
//把需要上传的data放进urlrequest里边
[urlrequest setHTTPBody:postData];
NSData *resultData = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:nil error:nil];
NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:resultData options:(NSJSONReadingAllowFragments) error:nil];
NSLog( @"dic1====%@",dic1);
}
#pragma GET异步:
//第一种:
- (IBAction)getY:(id)sender {
NSString *string = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?";
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//调用带有block回调的方法,执行网络请求
//第一个参数:NSURLRequest
//第二个参数:block块里边的代码在哪个线程执行
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//response 携带的是接口的一些信息
//data 请求下来的数据,需要使用的
//connectionnnError 错误信息
if (connectionError == nil) {
NSDictionary *dic2 = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
NSLog(@"dic2====%@",dic2);
//这里应该刷新UI
//1;给数据源数组赋值
//2;赋值结束后,刷新UI([self.tableview reloadData])
}
}];
}
//第二种方法
- (IBAction)get:(id)sender {
// 使用block回调的方式
// 使用系统提供的全局的NSURLSession对象,是一个单例
NSURLSession *session = [NSURLSession sharedSession];
NSString *string = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSURL *url = [NSURL URLWithString:string];
//NSURLSession是基于任务的,所以所有的东西都要放到任务里边, NSURLSessionTask就是 NSURLSession的任务执行对象
NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
NSLog(@"dic===%@", dic);
}
}];
// NSURLSession的所有任务默认是挂起的,所以一定要调用resume方法,让任务开始
[task resume];
}
//第三种方法 遵循NSURLSessionDataDelegate NSURLSession获取网络数据的代理协议
//NSURLSession代理的异步操作
//NSURLSession代理人的属性是只读的
//第一个参数:会话模式
//第二个参数:代理人
//第三个参数:代理方法在那个线程中进行
NSURLSession *session1 = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"];
//NSURLSessionDataTask的子类对象
NSURLSessionDataTask *dataTask = [session1 dataTaskWithURL:url];
[dataTask resume];
}
// 服务器开始响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
completionHandler(NSURLSessionResponseAllow);
self.resultdata = [NSMutableData data];
}
// 接收到数据
- (void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveData:(nonnull NSData *)data {
[self.resultdata appendData:data];
}
// 结束响应
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
if (error == nil) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.resultdata options:(NSJSONReadingAllowFragments) error:nil];
NSLog(@"Dictionary = %@", dict);
}
}
//第四种方法: 遵循NSURLConnectionDataDelegate协议
#pragma POST异步:
//第一种: 遵循NSURLConnectionDataDelegate协议
- (IBAction)postY:(id)sender {
NSString *string = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?";
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
NSString *datastr = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *postdata = [datastr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postdata];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
self.resultData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.resultData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:_resultData options:(NSJSONReadingAllowFragments) error:nil];
NSLog(@"%@", dic);
}
//第二种:session
- (IBAction)post:(id)sender {
NSURLSession *session = [NSURLSession sharedSession];
NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?";
NSURL *url = [NSURL URLWithString:str];
NSMutableURLRequest *urlrequest = [NSMutableURLRequest requestWithURL:url];
NSString *datastring = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *pdata = [datastring dataUsingEncoding:NSUTF8StringEncoding];
[urlrequest setHTTPMethod:@"POST"];
[urlrequest setHTTPBody:pdata];
NSURLSessionTask *task = [session dataTaskWithRequest:urlrequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
NSLog(@"%@", dic1);
}
}];
[task resume];
}
//第三种:
- (IBAction)postT:(id)sender {
NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlrequest = [NSMutableURLRequest requestWithURL:url];
//创建一个字符串
NSString *dataString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
//把这个字符串转换成NSData类型的对象
NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
//设置请求方式 方式为大写 如:POST GET
//GET请求可以不设置,但是POST请求必须设置
[urlrequest setHTTPMethod:@"POST"];
//把需要上传的data放进urlrequest里边
[urlrequest setHTTPBody:postData];
NSData *resultData = [NSURLConnection sendAsynchronousRequest:urlrequest returningResponse:nil error:nil];
NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:resultData options:(NSJSONReadingAllowFragments) error:nil];
NSLog( @"dic1====%@",dic1);
}
//第四种: 遵循NSURLSessionDataDelegate NSURLSession获取网络数据的代理协议
以上是关于GET,POST的同步和异步所有中代码方法的主要内容,如果未能解决你的问题,请参考以下文章