美文网首页
iOS post 传字符串

iOS post 传字符串

作者: 叩首问路梦码为生 | 来源:发表于2018-04-24 14:05 被阅读519次
    
    /**
     *  异步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];
    }
    

    相关文章

      网友评论

          本文标题:iOS post 传字符串

          本文链接:https://www.haomeiwen.com/subject/sjhjlftx.html