1. 程式人生 > >iOS https請求 NSURLSessionDataTask

iOS https請求 NSURLSessionDataTask

https error super sda eat ror auth 證書 params

//

// 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