AFN的使用(待整理)
待整理
一、文件下載
1.創建下載
//1.創建會話管理者 AFHTTPSessionManager *manager =[AFHTTPSessionManager manager]; NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; //2.下載文件 /* 第一個參數:請求對象 第二個參數:progress 進度回調 downloadProgress 第三個參數:destination 回調(目標位置) 有返回值 targetPath:臨時文件路徑 response:響應頭信息 第四個參數:completionHandler 下載完成之後的回調 filePath:最終的文件路徑 */ NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { //監聽下載進度 //completedUnitCount 已經下載的數據大小 //totalUnitCount 文件數據的中大小 NSLog(@"%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount); } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename]; NSLog(@"targetPath:%@",targetPath); NSLog(@"fullPath:%@",fullPath); return [NSURL fileURLWithPath:fullPath]; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { NSLog(@"%@",filePath); }]; //3.執行Task [download resume];
2.簡單下載工具類
+(void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure { //1.獲得請求管理者 AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager]; //2.發送Get請求 [mgr GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { success(responseObject); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }]; } +(NSURLSessionDataTask *)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure { //1.獲得請求管理者 AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager]; NSURLSessionDataTask *dataTask = [mgr POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { success(responseObject); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }]; return dataTask; }
三、文件上傳
#define Kboundary @"----WebKitFormBoundaryjv0UfA04ED44AhWx" #define KNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding] //1.創建會話管理者 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //2.1url NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"]; //2.2創建請求對象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //2.3 設置請求方法 request.HTTPMethod = @"POST"; //2.4 設請求頭信息 [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary] forHTTPHeaderField:@"Content-Type"]; //3.發送請求上傳文件 NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromData:[self getBodyData] progress:^(NSProgress * _Nonnull uploadProgress) { NSLog(@"%f",1.0 * uploadProgress.completedUnitCount/ uploadProgress.totalUnitCount); } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { NSLog(@"%@",responseObject); }]; //4.執行task [uploadTask resume]; } -(NSData *)getBodyData { NSMutableData *fileData = [NSMutableData data]; //5.1 文件參數 /* --分隔符 Content-Disposition: form-data; name="file"; filename="Snip20160225_341.png" Content-Type: image/png(MIMEType:大類型/小類型) 空行 文件參數 */ [fileData appendData:[[NSString stringWithFormat:@"--%@",Kboundary] dataUsingEncoding:NSUTF8StringEncoding]]; [fileData appendData:KNewLine]; //name:file 服務器規定的參數 //filename:Snip20160225_341.png 文件保存到服務器上面的名稱 //Content-Type:文件的類型 [fileData appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"Sss.png\"" dataUsingEncoding:NSUTF8StringEncoding]]; [fileData appendData:KNewLine]; [fileData appendData:[@"Content-Type: image/png" dataUsingEncoding:NSUTF8StringEncoding]]; [fileData appendData:KNewLine]; [fileData appendData:KNewLine]; UIImage *image = [UIImage imageNamed:@"Snip20160227_128"]; //UIImage --->NSData NSData *imageData = UIImagePNGRepresentation(image); [fileData appendData:imageData]; [fileData appendData:KNewLine]; //5.2 非文件參數 /* --分隔符 Content-Disposition: form-data; name="username" 空行 123456 */ [fileData appendData:[[NSString stringWithFormat:@"--%@",Kboundary] dataUsingEncoding:NSUTF8StringEncoding]]; [fileData appendData:KNewLine]; [fileData appendData:[@"Content-Disposition: form-data; name=\"username\"" dataUsingEncoding:NSUTF8StringEncoding]]; [fileData appendData:KNewLine]; [fileData appendData:KNewLine]; [fileData appendData:[@"123456" dataUsingEncoding:NSUTF8StringEncoding]]; [fileData appendData:KNewLine]; //5.3 結尾標識 /* --分隔符-- */ [fileData appendData:[[NSString stringWithFormat:@"--%@--",Kboundary] dataUsingEncoding:NSUTF8StringEncoding]]; return fileData; } -(void)upload2 { //1.創建會話管理者 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // NSDictionary *dictM = @{} //2.發送post請求上傳文件 /* 第一個參數:請求路徑 第二個參數:字典(非文件參數) 第三個參數:constructingBodyWithBlock 處理要上傳的文件數據 第四個參數:進度回調 第五個參數:成功回調 responseObject:響應體信息 第六個參數:失敗回調 */ [manager POST:@"http://120.25.226.186:32812/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { UIImage *image = [UIImage imageNamed:@"Snip20160227_128"]; NSData *imageData = UIImagePNGRepresentation(image); //使用formData來拼接數據 /* 第一個參數:二進制數據 要上傳的文件參數 第二個參數:服務器規定的 第三個參數:該文件上傳到服務器以什麽名稱保存 */ //[formData appendPartWithFileData:imageData name:@"file" fileName:@"xxxx.png" mimeType:@"image/png"]; //[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/Snip20160227_128.png"] name:@"file" fileName:@"123.png" mimeType:@"image/png" error:nil]; [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/Snip20160227_128.png"] name:@"file" error:nil]; } progress:^(NSProgress * _Nonnull uploadProgress) { NSLog(@"%f",1.0 * uploadProgress.completedUnitCount/uploadProgress.totalUnitCount); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"上傳成功---%@",responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"上傳失敗---%@",error); }]; }
四、AFN序列化處理
1.處理json //返回的是JSON數據 -(void)json { //1.創建會話管理者 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //http://120.25.226.186:32812/login?username=123&pwd=122&type=JSON NSDictionary *paramDict = @{ @"username":@"123", @"pwd":@"123", @"type":@"JSON" }; //2.發送GET請求 /* 第一個參數:請求路徑(不包含參數).NSString 第二個參數:字典(發送給服務器的數據~參數) 第三個參數:progress 進度回調 第四個參數:success 成功回調 task:請求任務 responseObject:響應體信息(JSON--->OC對象) 第五個參數:failure 失敗回調 error:錯誤信息 響應頭:task.response */ [manager GET:@"http://120.25.226.186:32812/login" parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"%@---%@",[responseObject class],responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"請求失敗--%@",error); }]; } //處理xml //返回的是XML -(void)xml { //1.創建會話管理者 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //http://120.25.226.186:32812/login?username=123&pwd=122&type=JSON //註意:如果返回的是xml數據,那麽應該修改AFN的解析方案 manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; NSDictionary *paramDict = @{ @"type":@"XML" }; //2.發送GET請求 /* 第一個參數:請求路徑(不包含參數).NSString 第二個參數:字典(發送給服務器的數據~參數) 第三個參數:progress 進度回調 第四個參數:success 成功回調 task:請求任務 responseObject:響應體信息(JSON--->OC對象) 第五個參數:failure 失敗回調 error:錯誤信息 響應頭:task.response */ [manager GET:@"http://120.25.226.186:32812/video" parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task,NSXMLParser *parser) { //NSLog(@"%@---%@",[responseObject class],responseObject); //NSXMLParser *parser =(NSXMLParser *)responseObject; //設置代理 parser.delegate = self; //開始解析 [parser parse]; } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"請求失敗--%@",error); }]; } //返回的二進制數據 -(void)httpData { //1.創建會話管理者 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //註意:如果返回的是xml數據,那麽應該修改AFN的解析方案AFXMLParserResponseSerializer //註意:如果返回的數據既不是xml也不是json那麽應該修改解析方案為: //manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //2.發送GET請求 [manager GET:@"http://120.25.226.186:32812/resources/images/minion_01.png" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject) { NSLog(@"%@-",[responseObject class]); //UIImage *image = [UIImage imageWithData:responseObject]; } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"請求失敗--%@",error); }]; } -(void)httpData2 { //1.創建會話管理者 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //註意:如果返回的是xml數據,那麽應該修改AFN的解析方案AFXMLParserResponseSerializer //註意:如果返回的數據既不是xml也不是json那麽應該修改解析方案為: //manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; //告訴AFN能夠接受text/html類型的數據 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //2.發送GET請求 [manager GET:@"http://www.baidu.com" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject) { NSLog(@"%@-%@",[responseObject class],[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]); //UIImage *image = [UIImage imageWithData:responseObject]; } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"請求失敗--%@",error); }]; } #pragma mark ---------------------- #pragma mark NSXMLParserDelegate -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict { NSLog(@"%@--%@",elementName,attributeDict); }
五、網絡監測
//1.獲得一個網絡狀態檢測管理者 AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager]; //2.監聽狀態的改變 /* AFNetworkReachabilityStatusUnknown = -1, 未知 AFNetworkReachabilityStatusNotReachable = 0, 沒有網絡 AFNetworkReachabilityStatusReachableViaWWAN = 1, 蜂窩網絡 AFNetworkReachabilityStatusReachableViaWiFi = 2 Wifi */ [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusReachableViaWWAN: NSLog(@"蜂窩網絡"); break; case AFNetworkReachabilityStatusReachableViaWiFi: NSLog(@"WIFI"); break; case AFNetworkReachabilityStatusNotReachable: NSLog(@"沒有網絡"); break; case AFNetworkReachabilityStatusUnknown: NSLog(@"未知"); break; default: break; } }]; //3.開始監聽 [manager startMonitoring]; }
六、加密類
#pragma mark - 散列函數 /** * 計算MD5散列結果 * * 終端測試命令: * @code * md5 -s "string" * @endcode * * <p>提示:隨著 MD5 碰撞生成器的出現,MD5 算法不應被用於任何軟件完整性檢查或代碼簽名的用途。<p> * * @return 32個字符的MD5散列字符串 */ - (NSString *)md5String; /** * 計算SHA1散列結果 * * 終端測試命令: * @code * echo -n "string" | openssl sha -sha1 * @endcode * * @return 40個字符的SHA1散列字符串 */ - (NSString *)sha1String; /** * 計算SHA256散列結果 * * 終端測試命令: * @code * echo -n "string" | openssl sha -sha256 * @endcode * * @return 64個字符的SHA256散列字符串 */ - (NSString *)sha256String; /** * 計算SHA 512散列結果 * * 終端測試命令: * @code * echo -n "string" | openssl sha -sha512 * @endcode * * @return 128個字符的SHA 512散列字符串 */ - (NSString *)sha512String; #pragma mark - HMAC 散列函數 /** * 計算HMAC MD5散列結果 * * 終端測試命令: * @code * echo -n "string" | openssl dgst -md5 -hmac "key" * @endcode * * @return 32個字符的HMAC MD5散列字符串 */ - (NSString *)hmacMD5StringWithKey:(NSString *)key; /** * 計算HMAC SHA1散列結果 * * 終端測試命令: * @code * echo -n "string" | openssl sha -sha1 -hmac "key" * @endcode * * @return 40個字符的HMAC SHA1散列字符串 */ - (NSString *)hmacSHA1StringWithKey:(NSString *)key; /** * 計算HMAC SHA256散列結果 * * 終端測試命令: * @code * echo -n "string" | openssl sha -sha256 -hmac "key" * @endcode * * @return 64個字符的HMAC SHA256散列字符串 */ - (NSString *)hmacSHA256StringWithKey:(NSString *)key; /** * 計算HMAC SHA512散列結果 * * 終端測試命令: * @code * echo -n "string" | openssl sha -sha512 -hmac "key" * @endcode * * @return 128個字符的HMAC SHA512散列字符串 */ - (NSString *)hmacSHA512StringWithKey:(NSString *)key; #pragma mark - 文件散列函數 /** * 計算文件的MD5散列結果 * * 終端測試命令: * @code * md5 file.dat * @endcode * * @return 32個字符的MD5散列字符串 */ - (NSString *)fileMD5Hash; /** * 計算文件的SHA1散列結果 * * 終端測試命令: * @code * openssl sha -sha1 file.dat * @endcode * * @return 40個字符的SHA1散列字符串 */ - (NSString *)fileSHA1Hash; /** * 計算文件的SHA256散列結果 * * 終端測試命令: * @code * openssl sha -sha256 file.dat * @endcode * * @return 64個字符的SHA256散列字符串 */ - (NSString *)fileSHA256Hash; /** * 計算文件的SHA512散列結果 * * 終端測試命令: * @code * openssl sha -sha512 file.dat * @endcode * * @return 128個字符的SHA512散列字符串 */ - (NSString *)fileSHA512Hash; #import <CommonCrypto/CommonCrypto.h> @implementation NSString (Hash) #pragma mark - 散列函數 - (NSString *)md5String { const char *str = self.UTF8String; uint8_t buffer[CC_MD5_DIGEST_LENGTH]; CC_MD5(str, (CC_LONG)strlen(str), buffer); return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH]; } - (NSString *)sha1String { const char *str = self.UTF8String; uint8_t buffer[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(str, (CC_LONG)strlen(str), buffer); return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)sha256String { const char *str = self.UTF8String; uint8_t buffer[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(str, (CC_LONG)strlen(str), buffer); return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH]; } - (NSString *)sha512String { const char *str = self.UTF8String; uint8_t buffer[CC_SHA512_DIGEST_LENGTH]; CC_SHA512(str, (CC_LONG)strlen(str), buffer); return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - HMAC 散列函數 - (NSString *)hmacMD5StringWithKey:(NSString *)key { const char *keyData = key.UTF8String; const char *strData = self.UTF8String; uint8_t buffer[CC_MD5_DIGEST_LENGTH]; CCHmac(kCCHmacAlgMD5, keyData, strlen(keyData), strData, strlen(strData), buffer); return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH]; } - (NSString *)hmacSHA1StringWithKey:(NSString *)key { const char *keyData = key.UTF8String; const char *strData = self.UTF8String; uint8_t buffer[CC_SHA1_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA1, keyData, strlen(keyData), strData, strlen(strData), buffer); return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)hmacSHA256StringWithKey:(NSString *)key { const char *keyData = key.UTF8String; const char *strData = self.UTF8String; uint8_t buffer[CC_SHA256_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA256, keyData, strlen(keyData), strData, strlen(strData), buffer); return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH]; } - (NSString *)hmacSHA512StringWithKey:(NSString *)key { const char *keyData = key.UTF8String; const char *strData = self.UTF8String; uint8_t buffer[CC_SHA512_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA512, keyData, strlen(keyData), strData, strlen(strData), buffer); return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - 文件散列函數 #define FileHashDefaultChunkSizeForReadingData 4096 - (NSString *)fileMD5Hash { NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self]; if (fp == nil) { return nil; } CC_MD5_CTX hashCtx; CC_MD5_Init(&hashCtx); while (YES) { @autoreleasepool { NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData]; CC_MD5_Update(&hashCtx, data.bytes, (CC_LONG)data.length); if (data.length == 0) { break; } } } [fp closeFile]; uint8_t buffer[CC_MD5_DIGEST_LENGTH]; CC_MD5_Final(buffer, &hashCtx); return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH]; } - (NSString *)fileSHA1Hash { NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self]; if (fp == nil) { return nil; } CC_SHA1_CTX hashCtx; CC_SHA1_Init(&hashCtx); while (YES) { @autoreleasepool { NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData]; CC_SHA1_Update(&hashCtx, data.bytes, (CC_LONG)data.length); if (data.length == 0) { break; } } } [fp closeFile]; uint8_t buffer[CC_SHA1_DIGEST_LENGTH]; CC_SHA1_Final(buffer, &hashCtx); return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)fileSHA256Hash { NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self]; if (fp == nil) { return nil; } CC_SHA256_CTX hashCtx; CC_SHA256_Init(&hashCtx); while (YES) { @autoreleasepool { NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData]; CC_SHA256_Update(&hashCtx, data.bytes, (CC_LONG)data.length); if (data.length == 0) { break; } } } [fp closeFile]; uint8_t buffer[CC_SHA256_DIGEST_LENGTH]; CC_SHA256_Final(buffer, &hashCtx); return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH]; } - (NSString *)fileSHA512Hash { NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self]; if (fp == nil) { return nil; } CC_SHA512_CTX hashCtx; CC_SHA512_Init(&hashCtx); while (YES) { @autoreleasepool { NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData]; CC_SHA512_Update(&hashCtx, data.bytes, (CC_LONG)data.length); if (data.length == 0) { break; } } } [fp closeFile]; uint8_t buffer[CC_SHA512_DIGEST_LENGTH]; CC_SHA512_Final(buffer, &hashCtx); return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - /** * 返回二進制 Bytes 流的字符串表示形式 * * @param bytes 二進制 Bytes 數組 * @param length 數組長度 * * @return 字符串表示形式 */ - (NSString *)stringFromBytes:(uint8_t *)bytes length:(int)length { NSMutableString *strM = [NSMutableString string]; for (int i = 0; i < length; i++) { [strM appendFormat:@"%02x", bytes[i]]; } return [strM copy]; }
//足夠長+足夠鹹+足夠復雜 #define salt @"shdcskjfcbskfnslfhs.kfsfvmsf8348390(*^^6R%@@IJEKHRKWKFGKF" //(明文+加鹽)MD5 NSLog(@"%@",[@"hello" md5String]); NSLog(@"%@",[[@"hello" stringByAppendingString:salt] md5String]); //先加密+亂序 //cb0fe21bfcc4c2625469d8ec6f3d710d--->12345 NSLog(@"%@",[@"hello" hmacMD5StringWithKey:@"world"]);
//對一個字符串進行base64編碼,並且返回 -(NSString *)base64EncodeString:(NSString *)string { //1.先轉換為二進制數據 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; //2.對二進制數據進行base64編碼,完成之後返回字符串 return [data base64EncodedStringWithOptions:0]; } //對base64編碼之後的字符串解碼,並且返回 -(NSString *)base64DecodeString:(NSString *)string { //註意:該字符串是base64編碼後的字符串 //1.轉換為二進制數據(完成了解碼的過程) NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:0]; //2.把二進制數據在轉換為字符串 return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; }
七、https
<NSURLSessionDataDelegate> AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //更改解析方式 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //設置對證書的處理方式 manager.securityPolicy.allowInvalidCertificates = YES; manager.securityPolicy.validatesDomainName = NO; [manager GET:@"https://kyfw.12306.cn/otn" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"success---%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"error---%@",error); }]; -(void)session { //1.確定url NSURL *url = [NSURL URLWithString:@"https://kyfw.12306.cn/otn"]; //2.創建請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.創建session NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; //4.創建Task NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { //5.解析數據 NSLog(@"%@---%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding],error); }]; //6.執行task [dataTask resume]; }
pragma mark NSURLSessionDataDelegate
//如果發送的請求是https的,那麽才會調用該方法
//challenge 質詢,挑戰
//NSURLAuthenticationMethodServerTrust
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
if(![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"])
{
return;
}
NSLog(@"%@",challenge.protectionSpace);
//NSURLSessionAuthChallengeDisposition 如何處理證書
/*
NSURLSessionAuthChallengeUseCredential = 0, 使用該證書 安裝該證書
NSURLSessionAuthChallengePerformDefaultHandling = 1, 默認采用的方式,該證書被忽略
NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 取消請求,證書忽略
NSURLSessionAuthChallengeRejectProtectionSpace = 3, 拒絕
*/
NSURLCredential *credential = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
//NSURLCredential 授權信息
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
AFN的使用(待整理)