iOS https请求 NSURLSessionDataTask
Posted qingjoin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS https请求 NSURLSessionDataTask相关的知识,希望对你有一定的参考价值。
//
// 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的主要内容,如果未能解决你的问题,请参考以下文章
iOS开发网络篇—发送GET和POST请求(使用NSURLSession)