分别使用AFN,NSURLConnection,NSURLSes

2019-06-24  本文已影响0人  MrJackyChen

AFN实现

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 15;
    // 设置非校验证书模式
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.HTTPShouldHandleCookies = YES;
    manager.requestSerializer.timeoutInterval = 15;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json;charset=utf8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:nil forHTTPHeaderField:@"Cookie"];
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookies = [NSArray arrayWithArray:[cookieJar cookies]];
    for (NSHTTPCookie *cookie in cookies) {
        if ([[cookie name] isEqualToString:@"JSESSIONID"]) {
            [cookieJar deleteCookie:cookie];
        }
    }
    
    [manager setSessionDidBecomeInvalidBlock:^(NSURLSession * _Nonnull session, NSError * _Nonnull error) {
        DDLogInfo(@"session invalid:%@",error);
    }];
    
    [manager setDataTaskDidReceiveResponseBlock:^NSURLSessionResponseDisposition(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSURLResponse * _Nonnull response) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if (httpResponse.statusCode == 420) {
            return NSURLSessionResponseCancel;
        }
        return NSURLSessionResponseAllow;
    }];
    
    [manager setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLAuthenticationChallenge * _Nonnull challenge, NSURLCredential *__autoreleasing  _Nullable * _Nullable credential) {
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (challenge.previousFailureCount == 0 ) {
            NSURLCredential *myCredential = [[NSURLCredential alloc]initWithUser:self.userNameTextField.text password:[self.pwdTextField.text MD5Hash]  persistence:NSURLCredentialPersistenceNone];
            *credential = myCredential;
            return NSURLSessionAuthChallengeUseCredential;
        }
        else{
            return NSURLSessionAuthChallengeCancelAuthenticationChallenge;
        }
        
    }];
    
    [manager POST:Login_Url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"登录成功");
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

采用NSURLConnection

需要遵守代理协议NSURLConnectionDelegate
点击登录按钮时

-(void)loginRequest{
    NSURL *url = [NSURL URLWithString:Login_Url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json;charset=utf8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:nil forHTTPHeaderField:@"Cookie"];
    NSURLConnection *connect = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connect start];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0) {
        NSLog(@"received authentication challenge");
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"USERNAME"
                                                                    password:@"PASSWORD"
                                                                 persistence:NSURLCredentialPersistenceNone];
        NSLog(@"credential created");
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        NSLog(@"responded to authentication challenge");
    }
    else {
        NSLog(@"previous authentication failure");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    DDLogInfo(@"didReceiveResponse:%@",response);
    if (httpResponse.statusCode == 200) {
        //执行登录成功后的操作
   ...    
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"didReceiveData:%@"data);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connectionDidFinishLoading:%@",connection);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
     NSLog(@"didFailWithError");
}

NSURLSession的实现方式

同样需要遵守NSURLSessionDelegate

-(void)loginRequest{
    NSURL *url = [NSURL URLWithString:Login_Url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json;charset=utf8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:nil forHTTPHeaderField:@"Cookie"];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse *respose = (NSHTTPURLResponse *)response;
        NSLog(@"NSURLSessionTask respose:%@",response);
    }];
    [task resume];
}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler{
    if (challenge.previousFailureCount == 0 && [[UIViewController currentViewController] isKindOfClass:[LoginViewController class]]) {
        NSURLCredential *myCredential = [[NSURLCredential alloc]initWithUser:@"USERNAME" password:@"PASSWORD" persistence:NSURLCredentialPersistenceNone];
        completionHandler(NSURLSessionAuthChallengeUseCredential,myCredential);
    }
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)aresponse{
    
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didCompleteWithError:(NSError *)error{
    
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
                             NSURLCredential *credential))completionHandler{
    
}


- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
        newRequest:(NSURLRequest *)request
 completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler{
    DDLogInfo(@"willPerformHTTPRedirection");
}

CFNetwork苹果开源库
下载解压后,在CFHTTPAuthentication.c文件中有这么一句话:

Once a 401 or a 407 is encountered, the authentication headers are parsed for all authentication types and their respective data
一旦遇到401或407,就会针对所有身份验证类型及其各自的数据解析身份验证标志头

在CFHTTPAuthentication.h头文件中有

Based on a response of 401 or 407, this function will create a
 *    new authentication object which can be used for adding
 *    credentials to future requests.
根据401或407的响应,此函数将创建
*可用于添加的新身份验证对象
*将来请求的凭据。

所以在坐挑战认证时服务端返回的状态码一定要是401或者407,要不然无法触发代理,进而无法进行认证。

如有问题后期会补充完善上来。

上一篇下一篇

猜你喜欢

热点阅读