标签:
1 /** 2 要使用常规的AFN网络访问 3 4 1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 5 6 所有的网络请求,均有manager发起 7 8 2. 需要注意的是,默认提交请求的数据是二进制的,返回格式是JSON 9 10 1> 如果提交数据是JSON的,需要将请求格式设置为AFJSONRequestSerializer 11 2> 如果返回格式不是JSON的, 12 13 3. 请求格式 14 15 AFHTTPRequestSerializer 二进制格式 16 AFJSONRequestSerializer JSON 17 AFPropertyListRequestSerializer PList(是一种特殊的XML,解析起来相对容易) 18 19 4. 返回格式 20 21 AFHTTPResponseSerializer 二进制格式 22 AFJSONResponseSerializer JSON 23 AFXMLParserResponseSerializer XML,只能返回XMLParser,还需要自己通过代理方法解析 24 AFXMLDocumentResponseSerializer (Mac OS X) 25 AFPropertyListResponseSerializer PList 26 AFImageResponseSerializer Image 27 AFCompoundResponseSerializer 组合 28 */ 29 30 - (void)viewDidLoad 31 { 32 [super viewDidLoad]; 33 34 [self reach]; 35 } 36 37 #pragma mark - 演练 38 #pragma mark - 检测网络连接 39 - (void)reach 40 { 41 /** 42 AFNetworkReachabilityStatusUnknown = -1, // 未知 43 AFNetworkReachabilityStatusNotReachable = 0, // 无连接 44 AFNetworkReachabilityStatusReachableViaWWAN = 1, // 3G 花钱 45 AFNetworkReachabilityStatusReachableViaWiFi = 2, // 局域网络,不花钱 46 */ 47 // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring 48 [[AFNetworkReachabilityManager sharedManager] startMonitoring]; 49 50 // 检测网络连接的单例,网络变化时的回调方法 51 [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 52 NSLog(@"%d", status); 53 }]; 54 } 55 56 #pragma mark - Session 下载 57 - (void)sessionDownload 58 { 59 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 60 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config]; 61 62 NSString *urlString = @"http://localhost/itcast/videos/01.C语言-语法预览.mp4"; 63 urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 64 65 NSURL *url = [NSURL URLWithString:urlString]; 66 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 67 68 NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 69 // 指定下载文件保存的路径 70 // NSLog(@"%@ %@", targetPath, response.suggestedFilename); 71 // 将下载文件保存在缓存路径中 72 NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; 73 NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename]; 74 75 // URLWithString返回的是网络的URL,如果使用本地URL,需要注意 76 NSURL *fileURL1 = [NSURL URLWithString:path]; 77 NSURL *fileURL = [NSURL fileURLWithPath:path]; 78 79 NSLog(@"== %@ |||| %@", fileURL1, fileURL); 80 81 return fileURL; 82 } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 83 NSLog(@"%@ %@", filePath, error); 84 }]; 85 86 [task resume]; 87 } 88 89 #pragma mark - POST JSON 90 - (void)postJSON 91 { 92 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 93 94 NSDictionary *dict = @{@"name": @"zhangsan"}; 95 NSDictionary *dict1 = @{@"name": @"wangwu"}; 96 NSArray *array = @[dict, dict1]; 97 // 设置请求格式 98 manager.requestSerializer = [AFJSONRequestSerializer serializer]; 99 // 设置返回格式 100 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 101 102 [manager POST:@"http://localhost/postjson.php" parameters:array success:^(AFHTTPRequestOperation *operation, id responseObject) { 103 NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 104 105 NSLog(@"%@", result); 106 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 107 108 }]; 109 110 } 111 112 #pragma mark - 随机文件名上传 113 - (void)postUpload1 114 { 115 // 本地上传给服务器时,没有确定的URL,不好用MD5的方式处理 116 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 117 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 118 119 [manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 120 121 NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil]; 122 123 // 要上传保存在服务器中的名称 124 // 使用时间来作为文件名 2014-04-30 14:20:57.png 125 // 让不同的用户信息,保存在不同目录中 126 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 127 // 设置日期格式 128 formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss"; 129 NSString *fileName = [formatter stringFromDate:[NSDate date]]; 130 131 [formData appendPartWithFileURL:fileURL name:@"uploadFile" fileName:fileName mimeType:@"image/png" error:NULL]; 132 133 } success:^(AFHTTPRequestOperation *operation, id responseObject) { 134 NSLog(@"OK"); 135 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 136 NSLog(@"error"); 137 }]; 138 } 139 140 #pragma mark - POST上传 141 - (void)postUpload 142 { 143 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 144 // AFHTTPResponseSerializer就是正常的HTTP请求响应结果:NSData 145 // 当请求的返回数据不是JSON,XML,PList,UIImage之外,使用AFHTTPResponseSerializer 146 // 例如返回一个html,text... 147 // 148 // 实际上就是AFN没有对响应数据做任何处理的情况 149 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 150 151 // formData是遵守了AFMultipartFormData的对象 152 [manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 153 154 // 将本地的文件上传至服务器 155 NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil]; 156 157 [formData appendPartWithFileURL:fileURL name:@"uploadFile" error:NULL]; 158 } success:^(AFHTTPRequestOperation *operation, id responseObject) { 159 NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 160 161 NSLog(@"完成 %@", result); 162 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 163 NSLog(@"错误 %@", error.localizedDescription); 164 }]; 165 } 166 167 #pragma mark - JSON 168 - (void)XMLData 169 { 170 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 171 172 // 返回的数据格式是XML 173 manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; 174 175 NSDictionary *dict = @{@"format": @"xml"}; 176 177 // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情 178 [manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { 179 180 // 如果结果是XML,同样需要使用6个代理方法解析,或者使用第三方库 181 // 第三方库第三方框架,效率低,内存泄漏 182 NSLog(@"%@", responseObject); 183 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 184 NSLog(@"%@", error); 185 }]; 186 } 187 188 #pragma mark - JSON 189 - (void)JSONData 190 { 191 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 192 193 // 原本需要拼接get访问URL ? & = 194 NSDictionary *dict = @{@"format": @"json"}; 195 196 // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情 197 [manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { 198 NSLog(@"%@", responseObject); 199 // 提问:NSURLConnection异步方法回调,是在子线程 200 // 得到回调之后,通常更新UI,是在主线程 201 NSLog(@"%@", [NSThread currentThread]); 202 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 203 NSLog(@"%@", error); 204 }]; 205 } 206 207 #pragma mark - POST登录 208 - (void)postLogin 209 { 210 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 211 212 // 原本需要拼接get访问URL ? & = 213 NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"}; 214 215 // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情 216 [manager POST:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { 217 NSLog(@"%@", responseObject); 218 // 提问:NSURLConnection异步方法回调,是在子线程 219 // 得到回调之后,通常更新UI,是在主线程 220 NSLog(@"%@", [NSThread currentThread]); 221 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 222 NSLog(@"%@", error); 223 }]; 224 } 225 226 #pragma mark - GET登录 227 - (void)getLogin 228 { 229 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 230 231 // 原本需要拼接get访问URL ? & = 232 NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"}; 233 234 // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情 235 [manager GET:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { 236 NSLog(@"%@", responseObject); 237 // 提问:NSURLConnection异步方法回调,是在子线程 238 // 得到回调之后,通常更新UI,是在主线程 239 NSLog(@"%@", [NSThread currentThread]); 240 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 241 NSLog(@"%@", error); 242 }]; 243 } 244
标签:
原文地址:http://www.cnblogs.com/mkai/p/5729685.html