需求
后台要求
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) {
}];
网友评论