1. 定义一个全局的AFHttpClient:包含有
1> baseURL
2> 请求
3> 操作队列 NSOperationQueue
2. 由AFHTTPRequestOperation负责所有的“网络”操作请求
完整demo:文件上传
关键代码:
1 - (IBAction)upload { 2 // 1.设置基准路径 3 AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://192.168.178.47:8080/MyServer"]]; 4 5 // 2.初始化请求参数 6 NSURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"upload" parameters:@{ 7 @"username" : @"carl", 8 @"pwd":@"123"} 9 constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 10 // 上传Default.png 11 [formData appendPartWithFileURL:[[NSBundle mainBundle] URLForResource:@"Default" withExtension:@"png"] name:@"file" error:nil]; 12 13 // 上传新获得的图片文件 14 NSData *data = UIImagePNGRepresentation(_imageView.image); 15 [formData appendPartWithFileData:data name:@"file" fileName:@"456.png" mimeType:@"image/png"]; 16 17 // 上传artifacts.xml 18 [formData appendPartWithFileURL:[[NSBundle mainBundle] URLForResource:@"artifacts" withExtension:@"xml"] name:@"file" error:nil]; 19 20 // 上传epl-v10.html 21 [formData appendPartWithFileURL:[[NSBundle mainBundle] URLForResource:@"epl-v10" withExtension:@"html"] name:@"file" error:nil]; 22 }]; 23 24 25 // 发送请求上传文件 26 AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:nil failure:nil]; 27 [operation start]; 28
时间: 2024-10-12 04:18:09