安全:GET请求(参数直接在网址中)是不安全的;POST请求(参数作为请求体单独提交)安全.

/**

       安全:GET请求(参数直接在网址中)是不安全的;POST请求(参数作为请求体单独提交)安全.

 */

/**

 同步连接和异步连接的区别:

 同步连接:网络请求任务交由主线程完成,当主线程请求数据时,所有的用户交互都无法处理,影响用户体验.

 异步连接:网络请求任务交由子线程去完成,当子线程请求数据时,主线程依然可以处理用户交互.用户体验好.

 */

GET:

//同步请求

- (IBAction)handleSychronize:(id)sender {

    //网址字符串.

    NSString *urlSrtr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";

    //网址字符串中若含汉字,特殊符号等,需要进行编码转化.

    //ios9之前采用的编码转换方法

//    [urlSrtr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

  urlSrtr = [urlSrtr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    //1.创建NSURL网址对象

    NSURL *url = [NSURL URLWithString:urlSrtr];

    //2.创建请求对象

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //3.连接服务器

    NSURLResponse *respondse = nil;//服务器的响应对象.

    NSError *error = nil;//存储链接失败的错误信息.

    /**

     *   同步请求:相当于把耗时的网络请求放到同一个线程(每一个程序至少有一个线程,平时写的代码都是主线程下执行的)中处理,当数据过大时,会产生界面卡顿.

     */

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

    //data就是我们通过网址从服务器请求到的数据.

}

//异步请求

- (IBAction)handleAsychronize:(id)sender {

    //网址字符串

    NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";

     //创建NSURL网址对象

    NSURL *url = [NSURL URLWithString:urlStr];

    //创建请求

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //连接服务器

    //参数2:[NSOperationQueue mainQueue] 获取主线程队列.  所给的线程决定block内部代码执行是在哪个线程下(UI界面上的刷新,用户交互,必须放在主线程执行.若在子线程中执行,可能会出现未知问题);

    //异步请求的第一种方式: block形式.

    /*

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

     //请求完成后才会回调, 返回对应的数据Data.

        //response  服务器响应对象

        //data 服务器返回的数据

        //connectionError  连接的错误信息

        //解析数据

        NSLog(@"%@",data);

    }];

     */

    //异步请求第二种方式:delegate形式

    [NSURLConnection connectionWithRequest:request delegate:self];

    

}

#pragma mark - NSURLConnectionDataDelegate -

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

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

    //该方法是在建立连接过程中触发的,只会执行一次.

    //再次创建NSMutableData对象 用于拼接返回的数据

    self.mutData = [NSMutableData data];

    //response服务器响应对象

    NSLog(@"%lld",response.expectedContentLength);

}

//接收到数据时

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

    [self.mutData appendData:data];

}

//数据传输结束时

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

    //解析数据

    NSLog(@"%@",self.mutData);

}

//连接失败时

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    NSLog(@"%@",error);

}

POST:

//同步请求

- (IBAction)handleSychrnize:(id)sender {

    //1.网址字符串

    NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";

    //2.若存在汉字或特殊符号  需编码转化

    //3.创建网址对象

    NSURL *url = [NSURL URLWithString:urlStr];

    //4.创建请求(可变请求对象)

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //5.创建参数字符串

    NSString *parmStr =@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";

    //6.参数字符串转为NSData

   NSData *body = [parmStr dataUsingEncoding:NSUTF8StringEncoding];

    //7.设置请求体

    [request setHTTPBody:body];

    //8.设置请求方式:(默认请求方式是GET);

    [request setHTTPMethod:@"POST"];

//requestHeader

NSDictionary *headers = [NSDictionary dictionaryWithObject:@"Bearer YWMtP_8IisA-EeK-a5cNq4Jt3QAAAT7fI10IbPuKdRxUTjA9CNiZMnQIgk0LEUE${token}" forKey:@"Authorization"];

    [request setAllHTTPHeaderFields:headers];



    //连接服务器,发送请求

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

    NSLog(@"%@",data);

}

//异步请求

- (IBAction)handleAsychrnize:(id)sender {

    //1.创建网址字符串

     NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";

    //2.创建网址对象

    NSURL *url = [NSURL URLWithString:urlStr];

    //3.创建请求对象

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //4.设置请求体

     //参数字符串

      NSString *parmStr =@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";

    NSData *body =[parmStr dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:body];

    //5.设置请求方式

    [request setHTTPMethod:@"POST"];

    //异步连接

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

        NSLog(@"%@",data);

    }];

}

session:

//

//  SessionViewController.m

//  UISenior-DataRequest

//

//  Created by Eric on 16/4/11.

//  Copyright © 2016年 Eric. All rights reserved.

//

#import "SessionViewController.h"

@interface SessionViewController ()<NSURLSessionDataDelegate>

{

    long long allBytes;//存储数据总长度;

}

@property(nonatomic,strong)NSMutableData *mData;

@end

@implementation SessionViewController

/**

NSURLConnection在ios9.0之后被弃用;

替代 使用NSURLSession 

 主要提供三种功能:1.数据请求:NSURLSessionDataTask

                             2.下载 :NSURLSessionDownloadTask

                             3.上传 : NSURLSessionUploadTask

 */

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    //获取数据

//    [self loadDataFromServer];

    //GET请求

//    [self getData];

    //POST请求

//    [self postAction];

    //获取数据

//    [self configureSession];

    //获取数据 使用delegate形式

    [self delegateAction];

}

//使用session代理的方式 请求数据

-(void)delegateAction{

    //1.URL

     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURLURLWithString:@"http://img.zcool.cn/community/0332de1559f800a32f875370ac09559.jpg"]];

    //使用代理形式请求数据:不能使用全局的对话对象

    NSURLSessionConfiguration *configure = [NSURLSessionConfiguration defaultSessionConfiguration];

    //创建session 创建的同时设置代理对象.

    NSURLSession *session = [NSURLSession sessionWithConfiguration:configure delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    //发起任务

  NSURLSessionDataTask *dataTask =  [session dataTaskWithRequest:request];

    //开启任务.

    [dataTask resume];

    

}

#pragma mark -NSURLSessionDelegate -

//服务器收到响应时

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{

    //允许响应  继续接受数据 (如果不写执行到此就结束)

    completionHandler(NSURLSessionResponseAllow);

    //创建mData

    self.mData = [NSMutableData data];

    allBytes = response.expectedContentLength;

}

//接收数据时

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData*)data{

    //每次返回一部分数据 需要拼接

    [self.mData appendData:data];

    //获取当前获取数据的百分比

 double scale = self.mData.length*1.0 /allBytes;

    self.scaleLable.text = [NSString stringWithFormat:@"%.2f%%",scale*100];

    self.image.image = [UIImage imageWithData:self.mData];

//    NSLog(@"%lf",scale);

}

//接收数据完成时

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError*)error{

    if (!error) {

        NSLog(@"%@",self.mData);

    }

}

//使用自己创建的Session发起任务.

//一般项目中,建议程序中少创建session,减少底层建立连接的过程.

- (void)configureSession{

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"]];

    //创建对话配置对象(对会话进行设置)

    /**

     *   支持三种类型:default默认的;

                               临时会话

                               后台

     */

    NSURLSessionConfiguration *configure = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:configure];

    //使用自己创建的会话创建任务.

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

        NSLog(@"%@",data);

    }];

    [task resume];

}

//POST请求

-(void)postAction{

    NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];

    //创建请求

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //设置请求方式

    [request setHTTPMethod:@"POST"];

    //设置请求体

    NSString *parmStr =@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";

    NSData *body = [parmStr dataUsingEncoding:NSUTF8StringEncoding];

    request.HTTPBody =body;

    //创建会话对象

    NSURLSession *session = [NSURLSession sharedSession];

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

        NSLog(@"%@",data);

    }];

    //手动开启任务.

    [dataTask resume];

}

//GET请求

-(void)getData{

    NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"];

    NSURLRequest *request = [NSURLRequest requestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:-1];

    //3. NSURLSession对象

    NSURLSession *session = [NSURLSession sharedSession];//获取系统为我们提供的全局绘画.

   //4.创建数据请求任务

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

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

     NSLog(@"%@",str);

 }];

    [task resume];

}

-(void)loadDataFromServer{

    //网址字符串

    NSString *str = @"http://img.zcool.cn/community/0332de1559f800a32f875370ac09559.jpg";

    //创建NSURL对象

    NSURL *url = [NSURL URLWithString:str];

    //创建请求

    /*参数①:网址对象

       参数②:缓存策略

       参数③: 超时时间 给-1代表不设置超时时间.

     */

    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    //使用session请求数据

    //创建一个NSURLSession对象(网络绘画对象)

    NSURLSession *session = [NSURLSession sharedSession];

    //请求数据 创建 NSURLSessionDataTask

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

      //data就是从服务器获取的数据.

      //response服务器响应对象

      //error 连接错误信息.

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

      //1.界面上的处理需要回到主线程,执行界面刷新任务

//      [self performSelectorOnMainThread:@selector(refreshUI:) withObject:data waitUntilDone:YES];

//2.GCD方式 回到主线程

     dispatch_async(dispatch_get_main_queue() , ^{

         self.image.image =[UIImage imageWithData:data];

     });

  }];

    //手动开始执行任务

    [dataTask resume];

}

//刷新界面操作

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

    self.image.image = [UIImage imageWithData:data];

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

@end

原文地址:https://www.cnblogs.com/wukun168/p/6010807.html