iOS https请求 NSURLSessionDataTask

摘要:
////YKSHttpsRequest.m//YKShareSdkDemo////Createdbyqingyunon22/05/2017.//Copyright2017qingjoin.Allrightsreserved.//#import“YKSHttps.h”@implementationYKSHttps Request+(YKSHttps-Request*)requestWith

//

//  YKSHttpsRequest.m

//  YKShareSdkDemo

//

//  Created by qingyun on 22/05/2017.

//  Copyright © 2017 qingjoin. All rights reserved.

//

#import "YKSHttpsRequest.h"

@implementation YKSHttpsRequest

+ (YKSHttpsRequest *)requestWithString:(NSString *)urlString {

    return [[YKSHttpsRequest alloc] initWithURLString:urlString];

}

- (id)initWithURLString:(NSString *)urlString {

    if (self = [super init]) {

        //转码成UTF8

        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        url = [NSURL URLWithString:urlString] ;

        NSLog(@"httpurl:%@",url);

        request = [NSURLRequest requestWithURL:url];

    }

    return self;

}

-(void)start

{

    //2.创建请求对象

    //3.创建session

    if(!request)

    {

        NSLog(@"requestNULL");

    }

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

    

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

        if (error) {

            

            NSLog(@"NSURLSessionDataTaskerror:%@",error);

            

        } else {

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

            NSLog(@"NSURLSessionDataTaskdic:%@",dic);

        }

        //5.解析数据

        NSLog(@"NSURLSessionDataTask:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

    }];

    //4.执行task

    [dataTask resume];

    

http://www.jianshu.com/p/8ff7269f2eff

}

//post请求

+ (void)postWithUrlString:(NSString *)url parameters:(id)parameters

{

    

    NSURL *nsurl = [NSURL URLWithString:url];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl];

    //设置请求方式

    request.HTTPMethod = @"POST";

    NSString *postStr = [YKSHttpsRequest parseParams:parameters];

    //设置请求体

    request.HTTPBody = [postStr dataUsingEncoding:NSUTF8StringEncoding];

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

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:queue];

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

        if (error) {

           // failureBlock(error);

        } else {

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

            //successBlock(dic);

             NSLog(@"NSURLSessionDataTaskdic:%@",dic);

        }

    }];

    [dataTask resume];

}

//把NSDictionary解析成post格式的NSString字符串

+ (NSString *)parseParams:(NSDictionary *)params

{

    NSString *keyValueFormat;

    NSMutableString *result = [NSMutableString new];

    NSMutableArray *array = [NSMutableArray new];

    //实例化一个key枚举器用来存放dictionary的key

    NSEnumerator *keyEnum = [params keyEnumerator];

    id key;

    while (key = [keyEnum nextObject]) {

        keyValueFormat = [NSString stringWithFormat:@"%@=%@&", key, [params valueForKey:key]];

        [result appendString:keyValueFormat];

        [array addObject:keyValueFormat];

    }

    return result;

}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler

{

    NSLog(@"URLSession :%@",challenge.protectionSpace);

    

    if (![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"])

        return;

    // 如果是请求证书信任,我们再来处理,其他的不需要处理

    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])

    {

        NSURLCredential *cre = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

        // 调用block

        completionHandler(NSURLSessionAuthChallengeUseCredential,cre);

        //SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;

        //completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:serverTrust]);

        

    } else

    {

        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);

    }

    

    /*

     NSURLSessionAuthChallengeUseCredential 使用证书

     NSURLSessionAuthChallengePerformDefaultHandling  忽略证书 默认的做法

     NSURLSessionAuthChallengeCancelAuthenticationChallenge 取消请求,忽略证书

     NSURLSessionAuthChallengeRejectProtectionSpace 拒绝,忽略证书

     */

    

    NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

    

    completionHandler(NSURLSessionAuthChallengeUseCredential,credential);

}

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

    

    

    NSLog(@"URLSessionXXXX%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

    

    

}

@end

免责声明:文章转载自《iOS https请求 NSURLSessionDataTask》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Eclipse 窗口说明vue路由传参以及接收参数的几种方法下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

iOS应用开发最佳实践系列一:编写高质量的Objective-C代码

      本文由海水的味道编译整理,转载请注明译者和出处,请勿用于商业用途! 点标记语法 属性和幂等方法(多次调用和一次调用返回的结果相同)使用点标记语法访问,其他的情况使用方括号标记语法。 良好的风格: view.backgroundColor = [UIColor orangeColor]; [UIApplication sharedAppl...

JS-OC通信之Cordova简介

Cordova 是一个可以让 JS 与原生代码(包括 Android 的 java,iOS 的 Objective-C 等)互相通信的一个库,并且提供了一系列的插件类,比如 JS 直接操作本地数据库的插件类。 这些插件类都是基于 JS 与 Objective-C 可以互相通信的基础的,这篇文章说说 Cordova 是如何做到 JS 与 Objective-...

MQTT-Client-FrameWork使用整理

作者: wbl MQTT MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是IBM开发的一个即时通讯协议,有可能成为物联网的重要组成部分。该协议支持所有平台,几乎可以把所有联网物品和外部连接起来,被用来当做传感器和制动器(比如通过Twitter让房屋联网)的通信协议 MQTT特点 MQTT协议是为大量计算...

iphone 数据存储之属性和归档archive

     在IPHONE中有四种方式可以永久存储数据分别是属性列表、归档、SQLITE3、coredata。前两者、后二者操作的时候有些地方是相同的,以属 性列表和归档来说都会用writeToFile/URL:path atomically:flag 和initWithContentofFile/URL:path;两都都不能直接操作基本数据类型,不过前者不...

QQ加群组件-iPhone、Android、网页上加入QQ群

iPhone代码: - (BOOL)joinGroup:(NSString *)groupUin key:(NSString *)key{ NSString *urlStr = [NSString stringWithFormat:@"mqqapi://card/show_pslcard?src_type=internal&version=1&a...

ios 清理缓存

//拿到要清理的路径,其实就是caches的路径,一般像这种很多地方都会用到的地方真好搞成宏,不过现在苹果不提倡用宏了 //在swift中可以定义成全局的常量 //遍历caches,将内部的文件大小计算出来,点击确认删除的话直接删除全部文件,如果有不想清理的文件,可以在遍历文件时根据路径过滤掉 {...