AFHTTPSessionManager标头

时间:2013-12-19 15:59:57

标签: ios objective-c afnetworking afnetworking-2

我正在尝试通过设置HTTPAdditionalHeaders为“Content-Type”设置默认标头。当我查看请求标头时,AFNetworking(v 2.0.3)将其更改回来。我还尝试在requestSerializer上使用setValue:forHTTPHeaderField:设置标头,但没有成功。我错过了什么?

已更新

    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");
    }];

3 个答案:

答案 0 :(得分:4)

我认为AFNetworking会自动设置Content-Type,您无法更改它。使用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) {

}];

答案 1 :(得分:1)

AFNetworking附带AFJSONRequestSerializerAFJSONResponseSerializer

[manager setRequestSerializer:[[AFJSONRequestSerializer alloc] init]];
[manager setResponseSerializer:[[AFJSONResponseSerializer alloc] init]];

答案 2 :(得分:1)

AFURLRequestSerialization.m文件中,您可以找到以下属性:

@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;

现在您可以继承AFHTTPRequestSerializer(或AFJSONRequestSerializer)并将所需的HTTP标头添加到该可变字典中(不要忘记在请求序列化程序中导入AFURLRequestSerialization.m文件.m文件)。

然后,您只需将requestSerializer子类的AFHTTPSessionManager属性设置为新请求序列化程序类的新对象(例如,在init方法中),并且您已完成。所有与会话管理器的请求都应包含您的HTTP标头。