网络请求

2016-05-17  本文已影响90人  简简简简简书

网络请求

http和https

URL

C/S模式

HTTPS

get和post

实现网络编程

str  = [str stringByAddingPercentEscapesUsingEncoding:[ NSCharacterSet URLQueryAllowedCharacterSet]];

NSURLConnection(ios9之后已经弃用了)

get请求

//定义的宏,一种是get用到的url,一种是post用到的url
#define KURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#define PURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
    //发送同步的get请求
    NSURL *url  =[NSURL URLWithString:KURL];
    //    NSLog(@"%@,%@",url.scheme,url.host);
    //    1.url 2.httpcache的方式 3.超时时间
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //    发送请求
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    if (data) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
        //response是响应(包含响应头和响应体)
        NSLog(@"%@",response);
    }
//异步get
    NSURL *url = [NSURL URLWithString:KURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    1.request 2. 主队列 3. 返回结果的block
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
    NSLog(@"先走这里");
   //代理异步get(事先引入代理NSURLConnectionDataDelegate)
- (void)delegateGet
{
    NSURL *url = [NSURL URLWithString:KURL];
    //    创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    连接
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    //    开始请求
    [connection start];
    //
    //    [connection cancel]; //取消
}
    //服务器接收到请求,开始响应,准备返回数据
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

}
//接收数据(如果data比较大,会走很多次,需要拼接)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //    把请求到的数据data拼接
    [self.data appendData:data];
}
//请求数据结束
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    id json = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"%@",json);
}
//失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

}

post

#pragma mark 异步post
//异步post
- (void)post
{
    //POST
    NSURL *url = [NSURL URLWithString:PURL];
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
    //    设置请求方式(post请求方式和参数必须设置)
    requset.HTTPMethod =@"POST";
    //    设置请求参数
    NSString *str =@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    requset.HTTPBody = data;
    //    设置请求头
    //    requset setValue:<#(nullable NSString *)#> forHTTPHeaderField:<#(nonnull NSString *)#>
    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
}
//代理异步post(代理方法与get是一样的,并且实现原理是相同的)
- (void)delegatePost
{
    NSURL *url = [NSURL URLWithString:PURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSString *str = @"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = data;
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
}

NSURLSession

get

- (void)blockGet
{
    //sessionGet
    //初始化session
    NSURLSession *session = [NSURLSession sharedSession];
    //    get请求
    NSURLSessionDataTask *task =[session dataTaskWithURL:[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"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
    //开启任务(默认挂起,需要手动开启)
    [task resume];
}
- (void)delegateGet
{
    //    控制任务的相关属性(事先引入代理NSURLSessionDataDelegate)
    NSURLSessionConfiguration *configuration =  [NSURLSessionConfiguration defaultSessionConfiguration];
    //初始化session
    //1.任务的控制面板 2.代理 3.代理回调的线程(一般是主线程)
    NSURLSession *session  = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[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"]];
    [dataTask resume];
}
//接收请求头
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //允许处理服务器的响应,才会继续接受服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);
}
//接收数据
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}
//结束接收数据或者出错
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (!error) {
        id json  = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"]];
    //设置请求方法
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding];
    //初始化
    NSURLSession  *session = [NSURLSession sharedSession];
    //创建任务
    NSURLSessionDataTask *datatask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //解析数据
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
//    开启
    [datatask resume];
上一篇下一篇

猜你喜欢

热点阅读