AFN 用post方式发送json格式的数据加上下边两句话就行了
session.requestSerializer = [AFJSONRequestSerializer serializer];
session.responseSerializer = [AFJSONResponseSerializer serializer];
/**
* post请求方法
*
* @param urlString 网络请求url
* @param parameters 网络请求参数
* @param success 请求成功的回调
* @param failure 请求失败的回调
*/
+ (void)postWithURLString:(NSString *)urlString parameters:(NSMutableDictionary *)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure
{
AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/plain", nil];
//post 发送json格式数据的时候加上这两句
// >>>>>>>>
session.requestSerializer = [AFJSONRequestSerializer serializer];
session.responseSerializer = [AFJSONResponseSerializer serializer];
// <<<<<<<<
session.requestSerializer.timeoutInterval = 15;
NSString *baseString = [NSString xxxx];
[session POST:baseString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
也可以这样: 但是推荐第一种方式
/**
post 请求发送json数据
@param urlString url
@param parameters 参数的 字典形式
@param success 成功的调用
@param failure 失败的调用
*/
+ (void)postJsonWithURLString:(NSString *)urlString parameters:(NSMutableDictionary *)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
NSDictionary *body = parameters;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSString *baseString = [NSString stringWithFormat:@"%@%@",REQ_HOST,urlString];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:baseString parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
//NSLog(@"Reply JSON: %@", responseObject);
success(responseObject);
} else {
//NSLog(@"Error: %@", error);
failure(error);
}
}] resume];
}