一.GET 请求方法
1.get同步请求
// Get
同步请求
- ( void )actionLeftButton:( UIBarButtonItem *)leftButton
{
// 创建网址对象
NSString *oldURL = kSearchURL ;
- ( void )actionLeftButton:( UIBarButtonItem *)leftButton
{
// 创建网址对象
NSString *oldURL = kSearchURL ;
//
如果你请求的网址中带有中文
得重新编码
NSString
*stringURL = [oldURL
stringByAddingPercentEscapesUsingEncoding
:
NSUTF8StringEncoding
];
//
把字符串变成网址对象
NSURL
*url = [
NSURL
URLWithString
:stringURL];
//
发出一个请求
// cachePolicy
缓存策略
一般选择默认的
timeoutInterval
请求超时时间
(
超过多少秒就
)
NSMutableURLRequest
*urlRequest = [
NSMutableURLRequest
requestWithURL
:url
cachePolicy
:(
NSURLRequestUseProtocolCachePolicy
)
timeoutInterval
:
30.0
];
//
默认
就是
Get
请求
NSURLRequest
如果要设置的话
需要使用可变请求
NSMutableURLRequest
//
设置请求类型
默认是
get
[urlRequest
setHTTPMethod
:
@"GET"
];
//
建立连接
//
接收二进制数据
//Response
服务器返回的
描述服务器的数据
// error
链接错误信息
NSURLResponse *response = nil ;
NSError *error = nil ;
NSData *data = [ NSURLConnection sendSynchronousRequest :urlRequest returningResponse :&response error :&error];
NSURLResponse *response = nil ;
NSError *error = nil ;
NSData *data = [ NSURLConnection sendSynchronousRequest :urlRequest returningResponse :&response error :&error];
//
要把
data
转化成
json
数据
NSMutableDictionary
*dataDic =[
NSJSONSerialization
JSONObjectWithData
:data
options
:(
NSJSONReadingMutableContainers
)
error
:
nil
];
NSLog ( @"----%@" , dataDic);
NSLog ( @"----%@" , dataDic);
}
2.get异步请求
// Get
异步请求
- (
void
)actionRightButton:(
UIBarButtonItem
*)rightButton
{
// 如果网址有中文 就要重新编码
NSString *new = [ kSearchURL stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding ];
{
// 如果网址有中文 就要重新编码
NSString *new = [ kSearchURL stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding ];
//
利用网址
创建一个网址对象
NSURL
*url = [
NSURL
URLWithString
:new];
//
利用网址对象
创建一个请求
NSMutableURLRequest
*request = [
NSMutableURLRequest
requestWithURL
:url
cachePolicy
:(
NSURLRequestUseProtocolCachePolicy
)
timeoutInterval
:
30
];
//
设置请求类型
[request setHTTPMethod:@"GET"];
#pragma mark
异步请求两种方法
1.Block
方法实现
/*
异步请求两种方法
:
1. // 建立一个异步请求的链接
// mainQueue 代表主线程
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 异步相当于开启一个子线程 去加载数据
// 数据加载完成 调用 Block 回到主线程
// 打印是否主线程
NSLog(@"%d", [NSThread isMainThread]);
1. // 建立一个异步请求的链接
// mainQueue 代表主线程
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 异步相当于开启一个子线程 去加载数据
// 数据加载完成 调用 Block 回到主线程
// 打印是否主线程
NSLog(@"%d", [NSThread isMainThread]);
}];
*/
#pragma mark 异步请求两种方法 2. 代理方法实现
// 注意 : ( 同步 异步有区别的地方 )
// 利用请求 创建一个链接
#pragma mark 异步请求两种方法 2. 代理方法实现
// 注意 : ( 同步 异步有区别的地方 )
// 利用请求 创建一个链接
//
遵守协议的名字
NSURLConnectionDataDelegate
self
.
connection
= [
NSURLConnection
connectionWithRequest
:request
delegate
:
self
];
// 开启异步请求
// 开启异步请求
[self.connection start];
}
#pragma mark --NSURLConnectionDataDelegate
代理方法
- (
void
)connection:(
NSURLConnection
*)connection didReceiveData:(
NSData
*)data
{
[self.data appendData:data];
NSLog
(
@"
接受数据时触发
"
);
}
- ( void )connection:( NSURLConnection *)connection didReceiveResponse:( NSURLResponse *)response
{
}
- ( void )connection:( NSURLConnection *)connection didReceiveResponse:( NSURLResponse *)response
{
//
触发方法
链接成功
初始化可变的
data
self
.
data
= [
NSMutableData
data
];
NSLog(@"
接受到服务器数据
,
说明链接成功了
."
);
}
- ( void )connectionDidFinishLoading:( NSURLConnection *)connection
{
// data
已经完整了
接下来可以解析
//
要把
data
转化成
json
数据
NSMutableDictionary *dataDic =[ NSJSONSerialization JSONObjectWithData : self . data options :( NSJSONReadingMutableContainers ) error : nil ];
NSLog ( @"----%@" , dataDic);
NSMutableDictionary *dataDic =[ NSJSONSerialization JSONObjectWithData : self . data options :( NSJSONReadingMutableContainers ) error : nil ];
NSLog ( @"----%@" , dataDic);
NSLog(@"
已经加载完成了
"
);
}
/**
* NSURLConnectionDelegate 代理的方法 报错了
*/
- ( void )connection:( NSURLConnection *)connection didFailWithError:( NSError *)error
{
NSLog ( @" 查看错误信息 " );
* NSURLConnectionDelegate 代理的方法 报错了
*/
- ( void )connection:( NSURLConnection *)connection didFailWithError:( NSError *)error
{
NSLog ( @" 查看错误信息 " );
}
二.POST
1.POST同步
//
同步
- ( void )actionLeftButton:( UIBarButtonItem *)leftButton
{
// 1. 创建网址对象
NSURL *url = [ NSURL URLWithString : kNewsListURL ];
// 2. 利用网址对象创建一个请求
NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL :url cachePolicy :( NSURLRequestUseProtocolCachePolicy ) timeoutInterval : 30 ];
// 3. 设置请求类型
[request setHTTPMethod : @"POST" ];
// 4. 注意 : 给这个请求携带一个请求体
NSData *data1 = [ kNewsListParam dataUsingEncoding : NSUTF8StringEncoding ];
// 携带到请求当中
[request setHTTPBody : data1];
// 5. 利用一个请求 创建一个链接并得到一个返回数据
NSData *data = [ NSURLConnection sendSynchronousRequest :request returningResponse : nil error : nil ];
NSMutableDictionary *dataDic = [ NSJSONSerialization JSONObjectWithData :data options :( NSJSONReadingMutableContainers ) error : nil ];
// 剥香蕉
NSLog ( @"%@" , dataDic);
- ( void )actionLeftButton:( UIBarButtonItem *)leftButton
{
// 1. 创建网址对象
NSURL *url = [ NSURL URLWithString : kNewsListURL ];
// 2. 利用网址对象创建一个请求
NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL :url cachePolicy :( NSURLRequestUseProtocolCachePolicy ) timeoutInterval : 30 ];
// 3. 设置请求类型
[request setHTTPMethod : @"POST" ];
// 4. 注意 : 给这个请求携带一个请求体
NSData *data1 = [ kNewsListParam dataUsingEncoding : NSUTF8StringEncoding ];
// 携带到请求当中
[request setHTTPBody : data1];
// 5. 利用一个请求 创建一个链接并得到一个返回数据
NSData *data = [ NSURLConnection sendSynchronousRequest :request returningResponse : nil error : nil ];
NSMutableDictionary *dataDic = [ NSJSONSerialization JSONObjectWithData :data options :( NSJSONReadingMutableContainers ) error : nil ];
// 剥香蕉
NSLog ( @"%@" , dataDic);
}
2.POST异步
//
异步
- ( void )actionRightButton:( UIBarButtonItem *)rightButton
{
// 1. 利用网址创建一个 url 网址对象
NSURL *url = [ NSURL URLWithString : kNewsListURL ];
// 2. 利用网址对象 创建请求
NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL :url cachePolicy :( NSURLRequestUseProtocolCachePolicy ) timeoutInterval : 30 ];
// 3. 设置请求的类型
[request setHTTPMethod : @"POST" ];
// 4. 给这个请求设置请求体
[request setHTTPBody :[ kNewsListParam dataUsingEncoding : NSUTF8StringEncoding ]];
// 5. 利用请求 创建链接 利用代理方法 实现异步请求数据
// (1)block 方法
// [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
// NSLog(@"========%@", dataDic);
// }];
// (2) 代理方法
self . connection = [ NSURLConnection connectionWithRequest :request delegate : self ];
// 开启链接
[ self . connection start ];
}
- ( void )connection:( NSURLConnection *)connection didReceiveResponse:( NSURLResponse *)response
{
self . data = [ NSMutableData data ];
NSLog ( @" 返回服务器信息 , 声明链接成功了 " );
}
- ( void )connection:( NSURLConnection *)connection didReceiveData:( NSData *)data
{
[ self . data appendData :data];
NSLog ( @" 每次返回一点数据 多次执行 " );
}
- ( void )connection:( NSURLConnection *)connection didFailWithError:( NSError *)error
{
NSLog ( @" 请求失败 , 错误信息 " );
}
- ( void )connectionDidFinishLoading:( NSURLConnection *)connection
{
NSMutableDictionary *dataDic = [ NSJSONSerialization JSONObjectWithData : self . data options :( NSJSONReadingMutableContainers ) error : nil ];
NSLog ( @"%@" , dataDic);
NSLog ( @" 完成请求此时可以进行数据解析 " );
- ( void )actionRightButton:( UIBarButtonItem *)rightButton
{
// 1. 利用网址创建一个 url 网址对象
NSURL *url = [ NSURL URLWithString : kNewsListURL ];
// 2. 利用网址对象 创建请求
NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL :url cachePolicy :( NSURLRequestUseProtocolCachePolicy ) timeoutInterval : 30 ];
// 3. 设置请求的类型
[request setHTTPMethod : @"POST" ];
// 4. 给这个请求设置请求体
[request setHTTPBody :[ kNewsListParam dataUsingEncoding : NSUTF8StringEncoding ]];
// 5. 利用请求 创建链接 利用代理方法 实现异步请求数据
// (1)block 方法
// [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
// NSLog(@"========%@", dataDic);
// }];
// (2) 代理方法
self . connection = [ NSURLConnection connectionWithRequest :request delegate : self ];
// 开启链接
[ self . connection start ];
}
- ( void )connection:( NSURLConnection *)connection didReceiveResponse:( NSURLResponse *)response
{
self . data = [ NSMutableData data ];
NSLog ( @" 返回服务器信息 , 声明链接成功了 " );
}
- ( void )connection:( NSURLConnection *)connection didReceiveData:( NSData *)data
{
[ self . data appendData :data];
NSLog ( @" 每次返回一点数据 多次执行 " );
}
- ( void )connection:( NSURLConnection *)connection didFailWithError:( NSError *)error
{
NSLog ( @" 请求失败 , 错误信息 " );
}
- ( void )connectionDidFinishLoading:( NSURLConnection *)connection
{
NSMutableDictionary *dataDic = [ NSJSONSerialization JSONObjectWithData : self . data options :( NSJSONReadingMutableContainers ) error : nil ];
NSLog ( @"%@" , dataDic);
NSLog ( @" 完成请求此时可以进行数据解析 " );
}
3.
Get
和
POST
的区别
1). get 请求 请求的网站全部明文显示 ( 安全性不高 )
2). get 请求 有字符数的限制 (255 个 )
3). post 请求 请求的网址不光是有一个请求的网址 还可以携带请求体 这个请求体 是以 nsdata 形式携带 所以安全性较高
4). post 请求 没有字符数限制
1). get 请求 请求的网站全部明文显示 ( 安全性不高 )
2). get 请求 有字符数的限制 (255 个 )
3). post 请求 请求的网址不光是有一个请求的网址 还可以携带请求体 这个请求体 是以 nsdata 形式携带 所以安全性较高
4). post 请求 没有字符数限制
一般公司都是用
post
请求
,
安全性高点
.
三.图片链接加载(异步)
@interface
ImageViewController
()<
NSURLConnectionDelegate
,
NSURLConnectionDataDelegate
>
@property ( nonatomic , retain ) UILabel *label;
@property ( nonatomic , retain ) UIImageView *imageView;
@property ( nonatomic , retain ) NSURLConnection *connection;
@property ( nonatomic , retain ) NSMutableData *data;
// 定义一个属性 记录总大小的
@property ( nonatomic , assign ) long long totalLength;
@end
@implementation ImageViewController
- ( void )dealloc
{
[ _connection cancel ];
[ _connection release ];
[ _label release ];
[ _imageView release ];
[ _data release ];
[ super dealloc ];
}
- ( void )viewDidLoad {
[ super viewDidLoad ];
self . navigationItem . title = @"Image" ;
UIBarButtonItem *leftButton = [[ UIBarButtonItem alloc ] initWithTitle : @" 加载图片 " style :( UIBarButtonItemStylePlain ) target : self action : @selector (actionLeftButton:)];
self . navigationItem . leftBarButtonItem = leftButton;
[ self addSubView ];
// Do any additional setup after loading the view.
}
- ( void )addSubView
{
self . imageView = [[ UIImageView alloc ] initWithFrame :[ self . view bounds ]];
[ self . view addSubview : self . imageView ];
self . imageView . backgroundColor = [ UIColor blackColor ];
self . label = [[ UILabel alloc ] initWithFrame : CGRectMake ( 100 , 100 , 100 , 40 )];
self . label . textAlignment = NSTextAlignmentCenter ;
self . label . backgroundColor = [ UIColor grayColor ];
[ self . imageView addSubview : self . label ];
[ _imageView release ];
[ _label release ];
}
// 请求用什么方法
- ( void )actionLeftButton:( UIBarButtonItem *)button
{
[ self setUpDataGet ];
}
- ( void )setUpDataGet
{
NSURL *url = [ NSURL URLWithString : kImageURL ];
NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL :url cachePolicy :( NSURLRequestUseProtocolCachePolicy ) timeoutInterval : 30 ];
[request setHTTPMethod : @"GET" ];
self . connection = [ NSURLConnection connectionWithRequest :request delegate : self ];
}
@property ( nonatomic , retain ) UILabel *label;
@property ( nonatomic , retain ) UIImageView *imageView;
@property ( nonatomic , retain ) NSURLConnection *connection;
@property ( nonatomic , retain ) NSMutableData *data;
// 定义一个属性 记录总大小的
@property ( nonatomic , assign ) long long totalLength;
@end
@implementation ImageViewController
- ( void )dealloc
{
[ _connection cancel ];
[ _connection release ];
[ _label release ];
[ _imageView release ];
[ _data release ];
[ super dealloc ];
}
- ( void )viewDidLoad {
[ super viewDidLoad ];
self . navigationItem . title = @"Image" ;
UIBarButtonItem *leftButton = [[ UIBarButtonItem alloc ] initWithTitle : @" 加载图片 " style :( UIBarButtonItemStylePlain ) target : self action : @selector (actionLeftButton:)];
self . navigationItem . leftBarButtonItem = leftButton;
[ self addSubView ];
// Do any additional setup after loading the view.
}
- ( void )addSubView
{
self . imageView = [[ UIImageView alloc ] initWithFrame :[ self . view bounds ]];
[ self . view addSubview : self . imageView ];
self . imageView . backgroundColor = [ UIColor blackColor ];
self . label = [[ UILabel alloc ] initWithFrame : CGRectMake ( 100 , 100 , 100 , 40 )];
self . label . textAlignment = NSTextAlignmentCenter ;
self . label . backgroundColor = [ UIColor grayColor ];
[ self . imageView addSubview : self . label ];
[ _imageView release ];
[ _label release ];
}
// 请求用什么方法
- ( void )actionLeftButton:( UIBarButtonItem *)button
{
[ self setUpDataGet ];
}
- ( void )setUpDataGet
{
NSURL *url = [ NSURL URLWithString : kImageURL ];
NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL :url cachePolicy :( NSURLRequestUseProtocolCachePolicy ) timeoutInterval : 30 ];
[request setHTTPMethod : @"GET" ];
self . connection = [ NSURLConnection connectionWithRequest :request delegate : self ];
}
- (
void
)connection:(
NSURLConnection
*)connection didFailWithError:(
NSError
*)error
{
}
- ( void )connection:( NSURLConnection *)connection didReceiveResponse:( NSURLResponse *)response
{
self . data = [ NSMutableData data ];
NSLog ( @" 开始 , 链接成功 " );
// 获取图片的大小
self . totalLength = response. expectedContentLength ;
}
- ( void )connection:( NSURLConnection *)connection didReceiveData:( NSData *)data
{
[ self . data appendData :data];
// 利用 data 加载图片
self . imageView . image = [ UIImage imageWithData : self . data ];
NSLog ( @" 一点一点传 " );
// 计算图片加载进度
_label . text = [ NSString stringWithFormat : @"%f" , ( float ) self . data . length / self . totalLength ];
}
- ( void )connectionDidFinishLoading:( NSURLConnection *)connection
{
NSLog ( @" 完成 " );
{
}
- ( void )connection:( NSURLConnection *)connection didReceiveResponse:( NSURLResponse *)response
{
self . data = [ NSMutableData data ];
NSLog ( @" 开始 , 链接成功 " );
// 获取图片的大小
self . totalLength = response. expectedContentLength ;
}
- ( void )connection:( NSURLConnection *)connection didReceiveData:( NSData *)data
{
[ self . data appendData :data];
// 利用 data 加载图片
self . imageView . image = [ UIImage imageWithData : self . data ];
NSLog ( @" 一点一点传 " );
// 计算图片加载进度
_label . text = [ NSString stringWithFormat : @"%f" , ( float ) self . data . length / self . totalLength ];
}
- ( void )connectionDidFinishLoading:( NSURLConnection *)connection
{
NSLog ( @" 完成 " );
}
四.prefixHeader文件
将头文件 或者 宏定义都写在这个文件里面
改路径