您的位置:首页 > 移动开发 > IOS开发

iOS请求数据两种方式(GET、POST)

2016-02-21 20:08 513 查看
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 = [NSURL
URLWithString:GETURL];

// 2、
创建请求对象,绑定URL

NSMutableURLRequest *request = [[NSMutableURLRequest
alloc]
initWithURL:url];

// 3、
发送请求

NSData *data = [NSURLConnection
sendSynchronousRequest:request returningResponse:nil
error:nil];

// NSLog(@"%@",data);

// json
解析

NSDictionary *dic = [NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingAllowFragments
error:nil];

// NSLog(@"%@",dic[@"news"]);

self.data = [NSMutableArray
array];

NSArray *array = dic[@"news"];

for (NSDictionary *dic
in array) {

News *news = [[News
alloc] init];

[news setValuesForKeysWithDictionary:dic];

[self.data
addObject:news];

}

for (News *news
in self.data) {

NSLog(@"%@ -- %@ -- %ld",news.title, news.NId, news.sequence);

}

}

#pragma mark ------ POST
方式进行同步请求

- (void)PostSyncAction {

//
生成创建URL对象

NSURL *url = [NSURL
URLWithString:POSTURL];

//
创建request对象

NSMutableURLRequest *request = [[NSMutableURLRequest
alloc]
initWithURL:url];

//
与get方式的两个不同

//
设置httpMethod

[request setHTTPMethod:@"POST"];

//
设置httpBody ,即传递参数

NSData *data = [POSTBODY
dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:data];

//
发送同步请求

NSData * dataRE = [NSURLConnection
sendSynchronousRequest:request returningResponse:nil
error:nil];

NSDictionary *dic = [NSJSONSerialization
JSONObjectWithData:dataRE options:NSJSONReadingAllowFragments
error:nil];

self.data = [NSMutableArray
array];

NSArray *arr = dic[@"news"];

for (NSDictionary *dict
in arr) {

News *news = [[News
alloc] init];

[news setValuesForKeysWithDictionary:dict];

[self.data
addObject:news];

}

for (News *news
in self.data) {

NSLog(@"%@ -- %@ -- %ld",news.title, news.NId, news.sequence);

}

}

#pragma mark ----------
使用Block方式实现异步请求

- (void)GETBlockAsyncAction {

// 1、创建URL

NSURL *url = [NSURL
URLWithString:GETURL];

// 2、创建请求对象

NSMutableURLRequest *request = [[NSMutableURLRequest
alloc]
initWithURL:url];

// 3、
发送异步请求

[NSURLConnection
sendAsynchronousRequest:request queue:[NSOperationQueue
mainQueue] completionHandler:^(NSURLResponse *
_Nullable response,
NSData * _Nullable data,
NSError * _Nullable connectionError) {

NSDictionary *dic = [NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingAllowFragments
error:nil];

self.data = [NSMutableArray
array];

NSArray *tempArray = dic[@"news"];

for (NSDictionary *dict
in tempArray) {

News *news = [[News
alloc] init];

[news setValuesForKeysWithDictionary:dict];

[self.data
addObject:news];

}

for (News *new
in self.data) {

NSLog(@"%@",new.title);

}

}];

}

#pragma mark --------GET
代理方式进行异步请求(引入<NSURLConnectionDataDelegate>)

- (void) GETDelegateAsyncAction {

// 1、创建URL对象

NSURL *url = [NSURL
URLWithString:GETURL];

// 2、
创建URLRequest对象

NSMutableURLRequest *request = [[NSMutableURLRequest
alloc]
initWithURL:url];

// 3、
同步和异步的不同

[NSURLConnection
connectionWithRequest:request delegate:self];

}

// 当收到服务器响应的时候

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

//
初始化结果数组

self.data = [NSMutableArray
array];

//
初始化缓冲水桶

self.tempData = [NSMutableData
data];

}

// 接收数据

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

// 将读取的部分数据拼接到水桶中

[self.tempData
appendData:data];

}

// 当所有的数据接收完毕的时候

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

// 对水桶中的所有数据进行解析

NSDictionary *dict = [NSJSONSerialization
JSONObjectWithData:self.tempData
options:NSJSONReadingAllowFragments
error:nil];

NSArray *array = dict[@"news"];

for (NSDictionary *dic
in array) {

News *news = [[News
alloc] init];

[news setValuesForKeysWithDictionary:dic];

[self.data
addObject:news];

}

//
循环打印,输出

for (News *news
in self.data) {

NSLog(@"%@",news.title);

}

}

二、 iOS9 之后(网络编程方式):POST异步实现、 GET异步实现

#pragma mark =========
使用iOS9的新方法进行post异步请求

- (IBAction)PostAction:(UIButton *)sender {

// 1、
创建URL

NSURL *url = [NSURL
URLWithString:POSTURL];

// 2、
创建请求对象

NSMutableURLRequest *request = [[NSMutableURLRequest
alloc]
initWithURL:url];

[request setHTTPMethod:@"POST"];

// 3、

NSData *bodyData = [POSTBODY
dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:bodyData];

#warning 新方法
的不同

// 4.1、
创建会话

NSURLSession *session = [NSURLSession
sharedSession];

// 4.2、
创建数据请求任务

NSURLSessionDataTask *task = [session
dataTaskWithRequest:request completionHandler:^(NSData *
_Nullable data, NSURLResponse *
_Nullable response,
NSError * _Nullable error) {

NSDictionary *dict = [NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingAllowFragments
error:nil];

NSLog(@"%@", dict);

}];

// 4.3、
启动任务

[task resume];

}

#pragma mark ==========
使用iOS9的新方法进行get异步请求

- (IBAction)GetAction:(UIButton *)sender {

// 1、
创建URL

NSURL *url = [NSURL
URLWithString:GETURL];

// 2、
创建请求对象

NSMutableURLRequest *request = [[NSMutableURLRequest
alloc]
initWithURL:url];

#warning iOS9的不同

// 3、
创建会话

NSURLSession *session = [NSURLSession
sharedSession];

// 4、
创建任务

NSURLSessionDataTask *tast = [session
dataTaskWithRequest:request completionHandler:^(NSData *
_Nullable data, NSURLResponse *
_Nullable response,
NSError * _Nullable error) {

NSDictionary *dict = [NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingAllowFragments
error:nil];

NSLog(@"%@",dict);

}];

// 5、开始任务

[tast resume];

}

三、 对新旧方法的两种封装, 在以后可以直接调用

旧方法(iOS9之前)

+ (void)solveDataWithUrl:(NSString *)stringUrl andHttpMethod:(NSString *)httpMethod andHttpBody:(NSString *)httpBody
andRevokeBlock:(DataBlock)block {

NSURL *url = [NSURL
URLWithString:stringUrl];

NSMutableURLRequest *request = [[NSMutableURLRequest
alloc]
initWithURL:url];

// 将所有的字母转换成大写

NSString *method = [httpMethod
uppercaseString];

if ([@"POST"
isEqualToString:method]) {

[request setHTTPMethod:httpMethod];

NSData *data = [httpBody
dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:data];

} else if ([@"GET"isEqualToString:method]){

} else {

// NSLog(@"方法类型参数错误");

@throw [NSException
exceptionWithName:@"WJ Param Error"
reason:@"方法类型参数错误"
userInfo:nil];

return;

}

[NSURLConnection
sendAsynchronousRequest:request queue:[NSOperationQueue
mainQueue] 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 = [NSURL
URLWithString:URL];

NSMutableURLRequest *request = [[NSMutableURLRequest
alloc]
initWithURL:url];

NSString *httpMethod = [method
uppercaseString];

if ([@"POST"
isEqualToString:httpMethod]) {

[request setHTTPMethod:httpMethod];

NSData *data = [httpMethod
dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:data];

} else if ([@"GET"
isEqualToString:httpMethod]) {

} else {

@throw [NSException
exceptionWithName:@"WJ Param Error"
reason:@"方法类型错误"
userInfo:nil];

return;

}

NSURLSession *session = [NSURLSession
sharedSession];

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 = [NSURL
URLWithString:stringUrl];

NSMutableURLRequest * request = [[NSMutableURLRequest
alloc]
initWithURL:url];

NSURLSession *session = [NSURLSession
sharedSession];

NSURLSessionDownloadTask *task = [session
downloadTaskWithRequest:request completionHandler:^(NSURL *
_Nullable location,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {

NSData *imageData = [NSData
dataWithContentsOfURL:location];

UIImage *image = [UIImage
imageWithData:imageData];

// 从子线程回到主线程进行界面更新

dispatch_async(dispatch_get_main_queue(), ^{

block(image);

});

}];

[task resume];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: