iOS网络编程

方法一:

 //01 URL

 NSURL  *url = [NSURL URLWithString:@"http://piao.163.com/m/movie/comm_list.html?app_id=1&mobileType=iPhone&ver=2.6&channel=appstore&deviceId=9E89CB6D-A62F-438C-8010-19278D46A8A6&apiVer=6&city=110000"];

    

 //02 构造 Request

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

  request.HTTPMethod = @"POST";

  request.timeoutInterval = 60;

  //Content-Type = application/x-www-form-urlencoded

  // [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    

  //设置请求体

  //page_size=20&movie_id=43485

  NSString *bodyStr = @"page_size=20&movie_id=43485";

  request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];;

    

    /**

     *  方法一,网络请求 在多线程中 ,当数据接收完毕 ,处理的block是在多线程 还是在主线程中运行取决于 queue参数,如果queuemainqueue, 数据的处理在主线程中,如果是其他queue则数据处理在多线程中

     */

//    //情景一 ,数据的解析处理需要花费很长时间

//    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

//    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

//        

//        //数据的接收在多线程中,如果 数据的解析时间很长,会阻塞,则数据的解析放在多线程中,刷新UI在主线程中

//    

//        NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

//        [NSThread sleepForTimeInterval:1];

//        

//        //刷新UI在主线程中

//       

//        dispatch_sync(dispatch_get_main_queue(), ^{

//             _textView.text = jsonStr;

//        });

//    }];

//

//    // 情景二  数据的解析处理时间很短

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

//        //数据的接收在多线程中,如果 数据的解析时间很短,不阻塞,则直接在主线程中 解析数据 然后刷新 UI

//        NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

//         _textView.text = jsonStr;

//        

//      }];

方法二:使用代理
1.创建URL
2.创建mutableURLrequest
3.设置该request
4.[NSURLConnection connectionWithRequest:request delegate:self];
需要遵守的协议:<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
一般用到的协议方法如下:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;(实时下载,可能被多次调用)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;  // 失败的处理

实例:音乐文件下载

/**

 *  

   一 内存优化 :如果缓冲区里面的数据超过500kb则把数据写到文件中

  断点续传 

 1)暂停的时候记录下载的位置

 2)继续下载时,告诉服务器从记录的位置开始传数据

 3)续传数据的时候,把数据写入到文件的末尾

 

 http协议的请求头的设置:

 Range : bytes=0-499   表示头500个字节

 Range : bytes=500-999 表示第二个500字节

 Range : bytes=-500    表示最后500个字节

 Range : bytes=500-    表示500字节以后的范围

 Range : bytes=0-0,-1  第一个和最后一个字节

 

 

 */



- (void)appendFile:(NSData *)data {

    

    //handle能够操作的前提是  文件已经创建

    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];

    

    //把文件的写位置 定位到 文件末尾

    [handle seekToEndOfFile];

    

    [handle writeData:data];

    [handle closeFile];

    

}


//NSUserDefaults 轻量数据保存

- (void)readUserDefaults {

    

    //读取plist文件 ,上一次保存的数据

    NSUserDefaults *userDefaults  = [NSUserDefaults standardUserDefaults];

    NSNumber *number = [userDefaults valueForKey:kTotalLen];

    totalLength = number.doubleValue;

    number = [userDefaults valueForKey:kReceivedLen];

    receivedLength = number.doubleValue;


}


- (void)writeUserDefaults {


    NSUserDefaults *userDefaults  = [NSUserDefaults standardUserDefaults];

    [userDefaults setValue:@(totalLength) forKey:kTotalLen];

    [userDefaults setValue:@(receivedLength) forKey:kReceivedLen];

    //把数据同步到文件中

    [userDefaults synchronize];

    

}


方法三:使用第三方库:AFNetWorking
github源码下载:https://github.com/AFNetworking/AFNetworking
翻译文档参考:http://www.tuicool.com/articles/zyEBjua

仅get请求
1.创建URL
2.创建mutableURLrequest
3.创建AFHTTPRequestOperation对象,创建时与mutableURLrequest对象关联
4.设置响应数据的解析格式,如json解析:
operation.responseSerializer = [AFJSONResponseSerializer serializer];
5. 设置数据传输完毕的   处理 block

- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

6. 把operation 添加到 queue
    queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];

get或者post请求
1.创建URL
2.创建AFHTTPRequestOperationManager对象manager
3.设置响应数据的解析格式,如json解析,manager.responseSerializer
4. - (AFHTTPRequestOperation *)POST:(NSString *)URLString

     parameters:(id)parameters

     success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;


- (AFHTTPRequestOperation *)GET:(NSString *)URLString

parameters:(id)parameters

success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure



其它:
Cookie
 NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    //获得所有cookie
    NSArray *cookies = [cookieStorage cookies];
    
    NSHTTPCookie *cookie = cookies[0];
    NSLog(@"第一条cookie %@",cookie);
    //cookie.name
    //cookie.expiresDate
    
    //获得某个url的cookie
   // [cookieStorage cookiesForURL:<#(NSURL *)#>]
   // NSLog(@"%@",cookies);


NSUrlSession (以后重点使用,iOS9中高要求)

参考官方文档:using nsurlsession
参考牛人博客:http://blog.csdn.net/majiakun1/article/details/38133433

 一 、session会话 有三种配置
 + (NSURLSessionConfiguration *)defaultSessionConfiguration; 默认的,缓存数据到硬盘上
 + (NSURLSessionConfiguration *)ephemeralSessionConfiguration; 短暂的,缓存数据到Ram中
 + (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier 后台任务

 二、session 启动 task有三种
 [session dataTaskWithURL:<#(NSURL *)#>];
 [session downloadTaskWithRequest:<#(NSURLRequest *)#>];
 [session uploadTaskWithRequest:<#(NSURLRequest *)#> fromData:(NSData *)];


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值