1 五.AFN 2 1.GET\POST 3 1> GET请求 4 // 1.获得请求管理者 5 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; 6 7 // 2.封装请求参数 8 NSMutableDictionary *params = [NSMutableDictionary dictionary]; 9 params[@"username"] = @"123"; 10 params[@"pwd"] = @"123"; 11 12 // 3.发送GET请求 13 [mgr GET:@"http://baidu.com/login" parameters:params 14 success:^(AFHTTPRequestOperation *operation, id responseObject) { 15 NSLog(@"请求成功---%@", responseObject); 16 } 17 failure:^(AFHTTPRequestOperation *operation, NSError *error) { 18 NSLog(@"请求失败---%@", error); 19 }]; 20 21 22 2> POST请求 23 // 1.获得请求管理者 24 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; 25 26 // 2.封装请求参数 27 NSMutableDictionary *params = [NSMutableDictionary dictionary]; 28 params[@"username"] = @"123"; 29 params[@"pwd"] = @"123"; 30 31 // 3.发送POST请求 32 [mgr POST:@"http://baidu.com/login" parameters:params 33 success:^(AFHTTPRequestOperation *operation, id responseObject) { 34 NSLog(@"请求成功---%@", responseObject); 35 } 36 failure:^(AFHTTPRequestOperation *operation, NSError *error) { 37 NSLog(@"请求失败---%@", error); 38 }]; 39 40 2.文件上传 41 // 1.获得请求管理者 42 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; 43 44 // 2.发送请求(做文件上传) 45 #warning parameters : 只能放非文件参数 46 NSMutableDictionary *params = [NSMutableDictionary dictionary]; 47 params[@"username"] = @"zhangsan"; 48 49 [mgr POST:@"http://baidu.com/upload" parameters:params 50 constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 51 // 一定要在这个block中添加文件参数 52 53 // 加载文件数据 54 NSString *file = [[NSBundle mainBundle] pathForResource:@"test.txt" ofType:nil]; 55 NSData *data = [NSData dataWithContentsOfFile:file]; 56 57 // 拼接文件参数 58 [formData appendPartWithFileData:data name:@"file" fileName:@"123.txt" mimeType:@"text/plain"]; 59 } 60 success:^(AFHTTPRequestOperation *operation, id responseObject) { 61 NSLog(@"上传成功----%@", responseObject); 62 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 63 NSLog(@"上传失败----%@", error); 64 }];
时间: 2024-12-14 22:41:14