美文网首页小问题程序猿阵线联盟-汇总各类技术干货
AFNetworking POST传递字符串(非JSON字符串)

AFNetworking POST传递字符串(非JSON字符串)

作者: 极客飞 | 来源:发表于2018-11-22 17:33 被阅读45次
需求

后台要求post方式调接口,参数只有一个字符串比如@"value"而非@{@"key":@"value"}。感觉总是有哪里和平时调接口不对,正常单独字符串参数(非json类型)的,都采取的是get方式,post一般传递的都是一个字典。后来找到方法,记录下来,以备后用,有同样疑惑的童鞋可以拿来用。

方法
/**
 *  异步POST请求:以body方式,支持数组
 *
 *  @param url     请求的url
 *  @param body    body数据(NSString 转为utf8编码的NSData就行)
 *  @param success 成功回调
 *  @param failure 失败回调
 */
- (void)PostWithUrlAndBody:(NSString *)url body:(NSData *)body success:(void(^)(NSDictionary *response))success failure:(void(^)(NSError *error))failure
{
    NSString *requestUrl = url;
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:requestUrl parameters:nil error:nil];
    request.timeoutInterval= 5.0;
    [request setValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[[NSUserDefaults standardUserDefaults]valueForKey:@"cookie"] forHTTPHeaderField:@"Cookie"];
    // 设置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) {
            success(responseObject);
        } else {
            failure(error);
        }
    }] resume];
}
调用
[self PostWithUrlAndBody:Nsite_ShareRevoke body:[[self.shareModel.dic objectForKey:@"id"] dataUsingEncoding:NSUTF8StringEncoding] success:^(NSDictionary *response) {
        } failure:^(NSError *error) {
        }];

相关文章

网友评论

    本文标题:AFNetworking POST传递字符串(非JSON字符串)

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