ios之AFN上传下载详细步骤(2)

时间:2024-12-21 14:37:20
 五.AFN
.GET\POST
> GET请求
// 1.获得请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 2.封装请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"";
params[@"pwd"] = @""; // 3.发送GET请求
[mgr GET:@"http://baidu.com/login" parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"请求成功---%@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败---%@", error);
}]; > POST请求
// 1.获得请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 2.封装请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"";
params[@"pwd"] = @""; // 3.发送POST请求
[mgr POST:@"http://baidu.com/login" parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"请求成功---%@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败---%@", error);
}]; .文件上传
// 1.获得请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 2.发送请求(做文件上传)
#warning parameters : 只能放非文件参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"zhangsan"; [mgr POST:@"http://baidu.com/upload" parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// 一定要在这个block中添加文件参数 // 加载文件数据
NSString *file = [[NSBundle mainBundle] pathForResource:@"test.txt" ofType:nil];
NSData *data = [NSData dataWithContentsOfFile:file]; // 拼接文件参数
[formData appendPartWithFileData:data name:@"file" fileName:@"123.txt" mimeType:@"text/plain"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"上传成功----%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"上传失败----%@", error);
}];