//

//  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的更多相关文章

  1. iOS使用自签名证书实现HTTPS请求

    概述 在16年的WWDC中,Apple已表示将从2017年1月1日起,所有新提交的App必须强制性应用HTTPS协议来进行网络请求. 默认情况下非HTTPS的网络访问是禁止的并且不能再通过简单粗暴的向 ...

  2. iOS ASIHTTPRequest 请求https

    iOS 终端请求服务端数据时,为了保证数据安全,我们一般会使用https协议加密,而对于iOS的网络编程,我们一般会使用开源框架:ASIHTTPRequest,但是如果使用传统的http方式,即使忽略 ...

  3. 为什么ios手机安装好fiddler证书/charles证书还是抓不到https请求?

    为什么ios手机安装好fiddler证书/charles证书还是抓不到https请求? 最近有不少人有此困惑, 因为你的ios系统应该是10.0以上的系统, 在手机系统设置---关于手机----证书信 ...

  4. fiddler抓取https请求(android/ios)

    本文转载自:http://blog.csdn.net/songer_xing/article/details/53841401 备注:本人有这样的一个需求,先记录下,以后再进行整理. 在抓包过程中发现 ...

  5. iOS 10.3下使用Fiddler抓取HTTPS请求

    最近使用Fiddler抓取手机上的HTTPS请求时,遇到一个问题.设置完之后,访问HTTPS的页面,却得到一个错误 网络出错,轻触屏幕重新加载:-1202 (如下图所示)   我印象中,之前都好好的, ...

  6. 十分钟学会Charles抓包(iOS的http/https请求)

    ### 原文地址,感谢作者 : http://www.jianshu.com/p/5539599c7a25 Charles安装 HTTP抓包 HTTPS抓包 1. Charles安装 官网下载安装Ch ...

  7. 43.Charles抓包(iOS的http/https请求)

    Charles安装 HTTP抓包 HTTPS抓包     1. Charles安装 官网下载安装Charles: https://www.charlesproxy.com/download/ 2. H ...

  8. iOS 用自签名证书实现 HTTPS 请求的原理

    在16年的WWDC中,Apple已表示将从2017年1月1日起,所有新提交的App必须强制性应用HTTPS协议来进行网络请求.默认情况下非HTTPS的网络访问是禁止的并且不能再通过简单粗暴的向Info ...

  9. Charles抓包(iOS的http/https请求)

    Charles抓包(iOS的http/https请求) Charles安装 HTTP抓包 HTTPS抓包 1. Charles安装 官网下载安装Charles:https://www.charlesp ...

随机推荐

  1. docker删除名字为none的imgae

    docker rmi $(docker images -f "dangling=true" -q)

  2. Ubuntu18.04上安装Docker CE

    建立 REPOSITORY 1.更新索引包 更新 /etc/apt/sources.list 和 /etc/apt/sources.list.d 中列出的源的地址,这样才能获取到最新的软件包 sudo ...

  3. 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。

    示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1 ...

  4. java的conllections.sort排序

    https://www.cnblogs.com/yw0219/p/7222108.html?utm_source=itdadao&utm_medium=referral

  5. Java 之 JavaScript (一)

    1.JavaScript a.定义:JavaScript 是脚本语言,是一种轻量级的编程语言 b.实现:①直接通过标签里面的onXX属性驱动js的执行 <input type="but ...

  6. HDU 1281 棋盘游戏 (枚举+最大匹配)

    <题目链接> Problem Description 小希和Gardon在玩一个游戏:对一个N*M的棋盘,在格子里放尽量多的一些国际象棋里面的“车”,并且使得他们不能互相攻击,这当然很简单 ...

  7. P3353 在你窗外闪耀的星星

    飞逝的的时光不会模糊我对你的记忆.难以相信从我第一次见到你以来已经过去了3年.我仍然还生动地记得,3年前,在美丽的集美中学,从我看到你微笑着走出教室,你将头向后仰,柔和的晚霞照耀着你玫瑰色的脸颊.我明 ...

  8. 016.OpenStack及云计算(面试)常见问题

    什么是云计算? 云计算是一种采用按量付费的模式,基于虚拟化技术,将相应计算资源(如网络.存储等)池化后,提供便捷的.高可用的.高扩展性的.按需的服务(如计算.存储.应用程序和其他 IT 资源).   ...

  9. javascript 作用域详解

    作用域理解:定义的变量.函数生效的范围.javascript 有全局作用域和函数作用域两种.注:es6实现let 块级作用域不是js原生的,底层同样是通过var实现的.如果想了解具体细节,请访问bab ...

  10. python 数据结构之归并排序

    def merger_sort(alist): if len(alist) <= 1 : return alist num=int(len(alist)/2) left=merger_sort( ...