AFNet上传 發表於 2016-07-10 | 上传 12345678910111213141516171819AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];NSDictionary *dict = @{@"username":@"hjs"};[manager POST:@"http://120.25.226.186:32812/upload" parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {NSURL *url = [NSURL fileURLWithPath:@"/Users/Programer/Desktop/桌面/20140701231656_tfNAZ.jpeg"];[formData appendPartWithFileURL:url name:@"file" error:nil];} success:^(NSURLSessionDataTask *task, id responseObject) {NSDictionary *res = responseObject;NSLog(@"%@",res);} failure:^(NSURLSessionDataTask *task, NSError *error) {if (error) {NSLog(@"失败");}}]; 下载 1234567891011121314151617181920212223242526AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_02.png"]];NSProgress *progress = nil;NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {NSString *cacheP = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];NSString *path = [cacheP stringByAppendingPathComponent:response.suggestedFilename];NSLog(@"%@",path);NSURL *url = [NSURL fileURLWithPath:path];return url;} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {}];//为进度添加观察者[progress addObserver:self forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:nil];[task resume]; get请求 12345678910AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];NSDictionary *parameters = @{@"username":@"hjsit",@"pwd":@"hjsit"};[manager GET:@"http://120.25.226.186:32812/login" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {NSLog(@"%@",[responseObject class]);} failure:^(NSURLSessionDataTask *task, NSError *error) {}]; 监听网络状态 12345678910111213141516171819202122232425262728// 1.创建网络监听管理者对象AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];// 2.设置监听/*AFNetworkReachabilityStatusUnknown = -1, 未识别AFNetworkReachabilityStatusNotReachable = 0, 未连接AFNetworkReachabilityStatusReachableViaWWAN = 1, 3GAFNetworkReachabilityStatusReachableViaWiFi = 2, wifi*/[manager setReachabilityStatusChangeBlock:^ void(AFNetworkReachabilityStatus status) {switch (status) {case AFNetworkReachabilityStatusNotReachable:NSLog(@"未连接");break;case AFNetworkReachabilityStatusReachableViaWWAN:NSLog(@"手机自带网络");break;case AFNetworkReachabilityStatusReachableViaWiFi:NSLog(@"wifi网络");break;default:NSLog(@"未识别");break;}}];// 3.开启监听[manager startMonitoring]; 序列化,数据返回类型 12345678910111213141516171819202122// 1.创建网络管理者AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];// 2.利用网络管理者发送get请求// NSDictionary *parameters = @{// @"username":@"hjsit",// @"pwd":@"hjsit",// @"type":@"XML"// };[AFJSONResponseSerializer serializer].acceptableContentTypes = [NSSet setWithObject:@"text/xml"];// 告诉AFN, 将返回的数据当做JSON来处理// manager.responseSerializer = [AFJSONRequestSerializer serializer];// 告诉AFN, 将返回的数据当做XML来处理// manager.responseSerializer = [AFXMLParserResponseSerializer serializer];// 告诉AFN, 将返回的数据当做二进制来数据 (服务器返回什么就是什么)manager.responseSerializer = [AFHTTPResponseSerializer serializer];[manager GET:@"http://120.25.226.186:32812/resources/images/minion_02.png" parameters:nil success:^ void(NSURLSessionDataTask * task, id responseObject) {NSLog(@"请求成功 %@", [responseObject class]);} failure:^ void(NSURLSessionDataTask * operation, NSError * error) {NSLog(@"请求失败 %@", error);}]; AFN推荐继承,推荐使用initWithBaseURL,单例 123456789101112+ (instancetype)shareNetworkTools2{static XMGNetworkTools2 *instance;static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/"];instance = [[self alloc] initWithBaseURL:url sessionConfiguration:cfg];});return instance;} AFN已经封装了HTTPS证书授权代码,直接可以请求,下面是证书授权代码 123456789101112131415161718192021222324*只要请求的地址是HTTPS的, 就会调用这个代理方法我们需要在该方法中告诉系统, 是否信任服务器返回的证书Challenge: 挑战 质问 (包含了受保护的区域)protectionSpace : 受保护区域NSURLAuthenticationMethodServerTrust : 证书的类型是 服务器信任*/- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{// NSLog(@"didReceiveChallenge %@", challenge.protectionSpace);NSLog(@"%@", challenge.protectionSpace.authenticationMethod);// 1.判断服务器返回的证书类型, 是否是服务器信任if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {NSLog(@"是服务器信任的证书");/*NSURLSessionAuthChallengeUseCredential = 0, 使用证书NSURLSessionAuthChallengePerformDefaultHandling = 1, 忽略证书(默认的处理方式)NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 忽略书证, 并取消这次请求NSURLSessionAuthChallengeRejectProtectionSpace = 3, 忽略当前这一次, 下一次再询问*/NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];completionHandler(NSURLSessionAuthChallengeUseCredential , credential);}}