今天简单介绍一下系统自带的网络数据请求方法,分为同步和异步的get和post。虽然现在程序猿们都用主流的数据请求工具AFN或者ASI,但是相对于一些简单的数据还是用系统的方法比较方法,至少不用导入相关的库。
一、先将一下同步请求数据(包括get和post)
1)get (对于那种后面直接带参数的网络地址用get请求)
NSString *str = @"http://....?name=张三&age=20"; //参数为name和age
NSString *strEcode = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];// 对中文进行编码
NSURL *url = [NSURL URLWithString:strEcode]; // 创建URL地址
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 创建可变请求对象
NSURLResponse *response = nil; // 将对象发给服务器
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data option:0 error:nil]; // 如果 请求数据返回是一个字典,就用字典接受。是json数据格式,故json解析方法解析。(这里先不讨论xml数据格式)
2)post (参数没有直接写在地址里,而是封装在一个body体里。优点:相对于get比较安全)
NSString *str = @"http://.... .ashx"; // 这里没有参数
NSURL *url = [NSURL URLWithString:str]; // 创建URL地址
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 创建可变请求对象
[request setHTTPMethod:@"POST"]; // 设置请求方式为post
NSString *bodyStr = @"name=张三&age=20"; // 设置参数
NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding]; // 将参数转为data型
[resquest setHTTPBody:data]; // 设置请求对象body体
NSURLResponse *response = nil; // 将对象发给服务器
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
二、异步请求
1)get
NSString *str = @"http://....?name=张三&age=20"; //参数为name和age
NSString *strEcode = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // 对中文进行编码
NSURL *url = [NSURL URLWithString:strEcode]; // 创建URL地址
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:30.f]; // 创建可变请求对象
[request setHTTPMethod:@"GET"]; // 设置请求方式
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
id objects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
// objects 即为返回的数据
}];
2) post
NSString *str = @"http://.... .ashx"; // 这里没有参数
NSURL *url = [NSURL URLWithString:str]; // 创建URL地址
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 创建可变请求对象
[request setHTTPMethod:@"POST"]; // 设置请求方式为post
NSString *bodyStr = @"name=张三&age=20"; // 设置参数
NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding]; // 将参数转为data型
[resquest setHTTPBody:data]; // 设置请求对象body体
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
id objects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
// objects 即为返回的数据
}];
注:由于xCode出了问题,所以代码只能纯手打,若有差错,望见谅。