AFNetworking 3.0+中使用body传数据

AFNetworking 3.0+中使用body传数据

此篇是接着上一篇 iOS PBEwithMD5andDes加密解密算法,由于刚从AFNetworking2.0+升级到了3.0+,由AFHTTPRequestOperationManager改为AFHTTPSessionManager,还是照着以前的写法改一改网络请求工具类,然后把NSData数据加到body里面,发现服务器端死活收不到,被这个问题卡了大半天都没辙。后面终于在网上看到了一个替代方案,就是使用AFURLSessionManager这玩意搞定了问题。

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

/**
 *  异步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头信息可能会根据服务器的要求做相应的修改。搞定!

你可能感兴趣的:(iOS项目记录,ios)