AFHTTPSessionManager标头 [英] AFHTTPSessionManager header
本文介绍了AFHTTPSessionManager标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过设置HTTPAdditionalHeaders为 Content-Type设置默认标题。当我查看请求标头时,AFNetworking(v 2.0.3)将其改回。我还尝试在requestSerializer上通过setValue:forHTTPHeaderField:设置标头,但没有成功。我缺少什么?
I am trying to set a default header for "Content-Type" by setting HTTPAdditionalHeaders. When I look at the request header, AFNetworking (v 2.0.3) changes it back. I also tried to set header by setValue:forHTTPHeaderField: on the requestSerializer, but no success. What I am missing?
更新
NSURL *URL = [NSURL URLWithString:@"http://example.com/api"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = @{@"Content-Type": @"multipart/form-data"};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:URL sessionConfiguration:configuration];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:@"some value" forKey:@"someKey"];
[manager POST:@"search" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"success");
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"error");
}];
推荐答案
我认为AFNetworking会自动设置Content-Type,而您无法更改。要使用Content-Type multipart / form-data发送数据,请执行以下操作:
I think that AFNetworking set Content-Type automatically and you can not change it. To send data using Content-Type multipart/form-data:
NSURL *URL = [NSURL URLWithString:@"http://example.com/api"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:URL sessionConfiguration:configuration];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:@"some value" forKey:@"someKey"];
[manager POST:@"search" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//If you need to send image
UIImage *image = [UIImage imageNamed:@"my_image.jpg"];
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.5) name:@"Image" fileName:@"my_image.jpg" mimeType:@"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
} failure:^(NSURLSessionDataTask *task, NSError *error) {
}];
这篇关于AFHTTPSessionManager标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文