网络请求

HTTP协议的常见请求方式以及连接方式



HTTP协议请求如何实现

第一步:创建请求

    NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
    NSURL *url = [NSURL URLWithString:str];
    
    // 创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];

讲一下:
NSMutableURLRequest 初始化方法第一个参数:请求访问路径 第二个参数:缓存协议 第三个参数:网络请求超时时间(秒)

NSURLRequestCachePolicy 枚举包含:
enum
{
    NSURLRequestUseProtocolCachePolicy = 0,(基本策略)

    NSURLRequestReloadIgnoringLocalCacheData = 1,(忽略本地缓存)
    NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented (<span style="font-family: Arial, Helvetica, sans-serif;">无视任何的缓存策略,无论是本地的还是远程的,总是从原地址重新下载</span><span style="font-family: Arial, Helvetica, sans-serif;">)</span>
    NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,

    NSURLRequestReturnCacheDataElseLoad = 2,(<span style="font-family: Arial, Helvetica, sans-serif;">首先使用缓存,如果没有本地缓存,才从原地址下载</span><span style="font-family: Arial, Helvetica, sans-serif;">)</span>
    NSURLRequestReturnCacheDataDontLoad = 3,(<span style="font-family: Arial, Helvetica, sans-serif;">使用本地缓存,从不下载,如果本地没有缓存,则请求失败。此策略多用于离线操作</span><span style="font-family: Arial, Helvetica, sans-serif;">)</span>

    NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented(如果本地缓存是有效的则不下载,其他任何情况都从原地址重新下载)
};
typedef NSUInteger NSURLRequestCachePolicy;

官方解释:
    @enum NSURLRequestCachePolicy

    @discussion The NSURLRequestCachePolicy enum defines constants that can be used to specify the type of interactions that take place with the caching system when the URL loading system processes a request. Specifically, these constants cover interactions that have to do with whether already-existing cache data is returned to satisfy a URL load request.

    @constant NSURLRequestUseProtocolCachePolicy Specifies that the  caching logic defined in the protocol implementation, if any, is  used for a particular URL load request. This is the default policy  for URL load requests.

    @constant NSURLRequestReloadIgnoringLocalCacheData Specifies that the data for the URL load should be loaded from the origin source. No existing local cache data,regardless of its freshness or validity, should be used to satisfy a URL load request.

    @constant NSURLRequestReloadIgnoringLocalAndRemoteCacheData Specifies that  not only should the local cache data be ignored, but that proxies and other intermediates should be instructed to disregard their caches so far as the protocol allows. Unimplemented.

    @constant NSURLRequestReloadIgnoringCacheData Older name for  NSURLRequestReloadIgnoringLocalCacheData.

    @constant NSURLRequestReturnCacheDataElseLoad Specifies that the existing cache data should be used to satisfy a URL load request, regardless of its age or expiration date. However, if there is no existing data in the cache corresponding to a URL load request, the URL is loaded from the origin source.

    @constant NSURLRequestReturnCacheDataDontLoad Specifies that the existing cache data should be used to satisfy a URL load request, regardless of its age or expiration date. However, if there is no existing data in the cache corresponding to a URL load request, no attempt is made to load the URL from the origin source, and the load is considered to have failed. This constant specifies a behavior that is similar to an "offline" mode.

    @constant NSURLRequestReloadRevalidatingCacheData Specifies that  the existing cache data may be used provided the origin source confirms its validity, otherwise the URL is loaded from the origin source.  Unimplemented.

第二步:设置请求方式

同步GET:
// 4.给请求 设置 请求方式
    [request setHTTPMethod:@"GET"];
同步POST:
    // 设置请求方式
    [request setHTTPMethod:@"POST"];
    // 设置post请求 附带数据
    // 产生一个body;
    NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
异步GET:
[request setHTTPMethod:@"GET"];
异步POST:
    [request setHTTPMethod:@"POST"];
    
    NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];

以上,可以总结 不论异步还是同步,GET请求都只是简单设置了 setHTTPMethod
而 POST请求 需要设置一个body

由此可见,GET操作简单,所有参数直接写到地址里面就可以了,POST操作复杂,需要将参数和地址分开写。
GET方式安全性不高,POS方式安全性比较高,参数放在body里面,不易被捕获。
GET方式地址(含参数)最多长度为255字节,多余的部分会被截掉.POST参数在body里面,所以即使内容再多也没关系。

第三步:连接服务器

同步GET:
    // 同步连接的方法 会一直等待数据完成接受后才继续执行
    NSError *error = nil;
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    // 现在获得的数据是完整的数据 data数据
    NSLog(@"获取的数据:%@", response);

同步POST:
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *dataBack = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"获取的数据:%@", response);
    NSString *result = [[NSString  alloc] initWithData:dataBack encoding:NSUTF8StringEncoding];
    NSLog(@"解析后的数据%@", result);

异步GET:
    // 参数1:设定请求
    // 参数2:设定代理人
    [NSURLConnection connectionWithRequest:request delegate:self];
// 当收到服务器的响应信息的时候 调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%s", __func__);
    // 当每次需要接收新的数据的时候 初始化data属性
    self.data = [NSMutableData data];
}

// 当收到服务器发送来的 data数据块 的时候 调用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"%s", __func__);
    [self.data appendData:data];
}

// 当数据接收完毕的时候调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%s", __func__);
    // 调用这个方法 说明 self.data 属性已经是一个完整的数据
    UIImage *image = [UIImage imageWithData:self.data];
    _imageView.image = image;
}

异步POST:
    // 建立异步连接
    // block基础上的异步连接
    // 参数1:请求
    // 参数2:返回主线程
    // 参数3:block
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 当异步连接完毕 而且 请求到完整数据(参数data)之后 才执行这个块内容
        
        // 在这个块中 写处理数据的代码 (解析/转为image/音频/视频)
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@", dic);
    }];

总结

网络请求的步骤:
1.NSURL
2.NSURLRequest
3.NSURLConnection
4.处理Error 或者 返回数据







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值