iOS AFNetworking 3.0+中使用body传数据

AFNetworking是我们常用的网络请求库,那么在3.0中怎么使用body传递数据给服务器。

废话不多说,直接上代码:

/**
 *  异步POST请求:以body方式,支持数组
 *
 *  @param url     请求的url
 *  @param body    body数据
 *  @param show    是否显示HUD
 *  @param success 成功回调
 *  @param failure 失败回调
 */
- (void)postWithUrl:(NSString *)url body:(NSData *)body showLoading:(BOOL)show success:(void(^)(NSDictionary *response))success failure:(void(^)(NSError *error))failure
{
    WS(weakSelf);
    if (show) {
        [weakSelf showLoading];
    }
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", kBaseUrl, url];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:requestUrl parameters:nil error:nil];
    request.timeoutInterval= TIME_OUT_INTERVAL;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // 设置body
    [request setHTTPBody:body];

    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                      @"text/html",
                                                                      @"text/json",
                                                                      @"text/javascript",
                                                                      @"text/plain",
                                                                      nil];
    manager.responseSerializer = responseSerializer;

    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        if (!error) {
            if (show) {
                [weakSelf dismissLoading];
            }
            success([weakSelf processResponse:responseObject]);

        } else {
            failure(error);
            [weakSelf showErrorMessage];
            ILog(@"request error = %@",error);
        }
    }] resume];
}

需要注意的是HTTP头信息可能会根据服务器的要求做相应的修改。