iOS https請求 NSURLSessionDataTask

來源:互聯網
上載者:User

標籤:queue   start   預設   處理   href   post請求   star   ini   seq   

 

 

 

 

//

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.