之前发送请求传给后台的参数都是 NSDictionary
类型的,最近后台要求传参数是 json
类型。
代码如下:
// 请求头
NSString *accessPath = @"http://xxx/getList";
// 请求参数字典
NSDictionary *params = @{@"type":@"1", @"name":@"2"};
NSLog(@"发送请求url=%@,params=%@",accessPath,params);
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:accessPath parameters:params error:nil];
request.timeoutInterval = 10.f;
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSLog(@"-----responseObject===%@+++++",responseObject);
if (!error) {
if ([responseObject isKindOfClass:[NSDictionary class]]) {
// 请求成功数据处理
} else {
}
} else {
NSLog(@"请求失败error=%@", error);
}
}];
[task resume];
说明:
找了一圈无果,最后在 AFNetworking请求序列化 介绍里面找到了,图样图森破啊。翻译如下:
AFNetworking
请求序列化:
请求序列化通过请求的URL字符串创建请求,编码参数作为查询字符串或HTTP体。以下面请求为例:
NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
- 1、查询字符串参数编码
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
- 2、URL表单参数编码
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/Content-Type: application/x-www-form-urlencodedfoo=bar&baz[]=1&baz[]=2&baz[]=3
- 3、JSON参数编码
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/Content-Type: application/json{"foo": "bar", "baz": [1,2,3]}
第三种就是我们要求的,搞定~