ios urlsession html,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];

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值