有时进行网络请求是需要将参数设置到请求体的body里面,又称将对象作为参数传入后台,params视情况而定 我是用的是AFNetworking,代码如下,里面有详细注释
- (void)startRequestWithUrl:(NSString *)url method:(NSString *) method params:(NSDictionary *)params{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//method 为时post请求还是get请求
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:url parameters:nil error:nil];
//设置超时时长
request.timeoutInterval= 30;
//设置上传数据type
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//设置接受数据type
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSString *token = @"123456789098765432";
[request setValue:token forHTTPHeaderField:@"token"];
//将对象设置到requestbody中 ,主要是这不操作
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
//进行网络请求
[[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
} downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(@"Reply JSON: %@", responseObject);
} else {
NSLog(@"Error: %@, %@, %@", error, response, responseObject);
}
}] resume];
}
参数格式如下:
{
"xxx": "xxxxxx",
"xxxx": [
{
"xxxx": "xxxx",
"xxxx": "xxxx"
}
]
}
网友评论