AFNetWroking 3.0 GET&POST基本使用

时间:2024-04-27 17:04:53
```
- (void)requestWithUrl:(NSString *)url params:(NSDictionary *)params methodType:(NSString *)methodType{
// 1. 创建URLString
if (url == nil) {
url = [[IMConfigManager defaultManager] getNewsAppUrl];
} // 2. 创建SessionConfiguration
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 3. 创建SessionManager
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
// 4. 创建Request
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:methodType URLString:url parameters:params error:nil]; // 5. 设置Response
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil]; if ([methodType isEqualToString:@"POST"]) {
// 设置application的HTTPHeaderField
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
} // 6. 创建SessionDataTask
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
[self requestFailure:error];
} else { [self requestSuccess:response responseObject:responseObject];
}
}]; // 7. 执行SessionDataTask
[dataTask resume];
} ```