项目需要在网络请求的时候把相关参数包在body里面,由于之前这类操作遇到的较少,所以在这儿做下记录,具体代码如下:
NSString *dicTojson = @"字典转字符串的参数";
NSString *url = [NSString stringWithFormat:@"%@VMS2Service.cgi?Cmd=%@",baseUrl, method];
NSData *body = [dicTojson dataUsingEncoding:NSUTF8StringEncoding]
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer]requestWithMethod:requestType URLString:url parameters:nil error:nil];
[request setHTTPMethod:requestType];
[request setValue:authToken forHTTPHeaderField:@"Auth-Token"];
[request setHTTPBody:body];
//设置超时时间
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.timeoutIntervalForRequest = 15.0;
sessionConfig.timeoutIntervalForResource = 15.0;
NSURLSession *session = [NSURLSession sharedSession];;
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(error==nil){
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (failure) {
failure(errorMsg);
}
}else{
if(success){
success(dict);
}
}
}else{
if (failure) {
failure(@"服务器超时");
}
}
} ];
[dataTask resume];
AFN方式的可以用参考: ios 使用AFNetworking 将对象作为参数(放入body)传给后台 - 简书