首页 > 代码库 > AFN的使用(待整理)
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 = http://www.mamicode.com/[NSMutableData data];"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 = http://www.mamicode.com/key.UTF8String;"%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的使用(待整理)