如何使用AFNetworking 2.0发布数据?

时间:2014-01-16 03:31:21

标签: ios web-services networking post afnetworking-2

我需要通过POST以可变数据发送我的数据。

我这样做:

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"email" : email, @"password" : pass };
[manager POST:URLString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:
 ^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"Error: %@", error); }];

并且:

JSON: {
Data = "<null>";
Message = "unexpected end of JSON input";
Result = fail;
}

我知道方法

  - (AFHTTPRequestOperation *)POST:(NSString *)URLString
                  parameters:(NSDictionary *)parameters
   constructingBodyWithBlock:(void (^)(id <AFMultipartFormData>))block
                     success:(void (^)(NSURLSessionDataTask *, id))success
                     failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

但是如何将可变数据中的字典发送到Web服务器?

1 个答案:

答案 0 :(得分:11)

您的Web服务是否希望将参数格式化为JSON?如果是这样,在调用POST方法之前,您需要告诉manager使用JSON requestSerializer,即AFJSONRequestSerializer

manager.requestSerializer = [AFJSONRequestSerializer serializer];

默认情况下,AFNetworking假定您要使用AFHTTPRequestSerializer(即Content-Type application/x-www-form-urlencoded {{1}}的请求。