今天记录一下afn 请求参数要以body的方式传递给后台。下面是核心代码:
-(void)requestBody{
//参数
NSDictionary *params = @{@"key1":@"value1",@"key2":@"value2"};
//参数转data
NSData *dataBody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//初始化请求 request
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
request.timeoutInterval = 60.f;
//设置请求头格式
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//设置请求体 body
[request setHTTPBody:dataBody];
//初始化请求管理 manager
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript", @"text/plain", @"application/javascript", nil];
manager.responseSerializer = responseSerializer;
//开始请求 resume(启动请求---很重要的一步,否则请求不启动)
[[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
} downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil]; //解析
NSLog(@"%@",jsonData);
} else {
NSLog(@":%@",error);
}
}] resume];
}
/**
* NSDictionary-->NSString(json形式的)
*/
- (NSString*)convertToJSONData:(id)infoDict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString = @"";
if (!jsonData){
NSLog(@"Got an error: %@", error);
}else{
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
jsonString = [jsonString stringByReplacingOccurrencesOfString:@" " withString:@""];// 去掉空格
//jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];// 去掉斜杠
return jsonString;
}