我正在使用AFNetworking 2.0,在这里我必须在身体部分传递json对象,如何在AFHTTPRequestOperationManager中传递HTTP Body。
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
谢谢,
答案 0 :(得分:0)
离线聊天,听起来主要关注的是如何在单个请求中发送个人资料图片,姓名,电子邮件地址,用户ID和密码。它可能看起来像:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSURL *filePath = ...
[manager POST:@"http://example.com/registration.json" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"image" error:nil];
[formData appendPartWithFormData:[name dataUsingEncoding:NSUTF8StringEncoding] name:@"name"];
[formData appendPartWithFormData:[email dataUsingEncoding:NSUTF8StringEncoding] name:@"email"];
[formData appendPartWithFormData:[userid dataUsingEncoding:NSUTF8StringEncoding] name:@"userid"];
[formData appendPartWithFormData:[password dataUsingEncoding:NSUTF8StringEncoding] name:@"password"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
不需要JSON。
如果您想使用JSON,可以这样做,但不会使用constructingBodyWithBlock
方法(创建multipart/form-data
请求)。相反,您只需创建一个普通的旧JSON请求,例如:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = @{
@"name" : name,
@"email" : email,
@"userid" : userid,
@"password" : password,
@"image" : base64EncodedImage
};
[manager POST:@"http://example.com/registration.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
显然,这些是非常不同的方法,因此无论采用何种方法,都需要编写服务器代码来处理相同的API。