//

//  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. 学习Spring必须了解的基础知识——回调机制

    上面这张图如果能看得懂就能理解什么是回调机制: A对象在调用a()方法时会调用B对象的b()方法,b()方法必须能调用A对象的callback()方法. 谁白了:a()方法有B对象b()方法的引用,b ...

  2. 009 pandas的Series

    一:创建 1.通过Numpy数组创建 2.属性查看 3.一维数组创建(与numpy的创建一样) 4.通过字典创建 二:应用Numpy数组运算 1.获取值 numpy的数组运算,在Series中都被保留 ...

  3. 068 mapWithState函数的讲解

    1.问题 主要是updateStateByKey的问题 有的值不需要变化的时候,还会再打印出来. 每个批次的数据都会出现,如果向redis保存更新的时候,会把不需要变化的值也更新,这个不是我们需要的, ...

  4. mybatis提示Invalid bound statement (not found)错误的可能原因

    https://www.cnblogs.com/liaojie970/p/8034525.html

  5. execution(* com.sample.service.impl..*.*(..))

    execution(* com.sample.service.impl..*.*(..)) 解释如下: 符号 含义 execution() 表达式的主体: 第一个”*“符号 表示返回值的类型任意: c ...

  6. 使用Chrome浏览器设置XX-net的方法

        以下介绍使用Chrome浏览器设置XX-net的方法 1.下载并安装谷歌浏览器. 2.打开https://github.com/XX-net/XX-Net/blob/master/code/d ...

  7. Sudoku POJ - 3076 (dfs+剪枝)

    Description A Sudoku grid is a 16x16 grid of cells grouped in sixteen 4x4 squares, where some cells ...

  8. componentWillReceiveProps详解(this.props)状态改变检测机制

    参考资料:http://blog.csdn.net/ElinaVampire/article/details/51813677 大家先看一张关于组件挂载的经典的图片: 下面一一说一下这几个生命周期的意 ...

  9. 一个完整的Java程序示例

    (1) 第一个程序HelloWorld: package mypack; //相当于一个目录 public class HelloWorld{ public static void main(Stri ...

  10. C语言中存储类别又分为四类:自动(auto)、静态(static)、寄存器的(register)和外部的(extern)。

    除法运算中注意: 如果相除的两个数都是整数的话,则结果也为整数,小数部分省略,如8/3 = 2:而两数中有一个为小数,结果则为小数,如:9.0/2 = 4.500000. 取余运算中注意: 该运算只适 ...