如何使用AFNetworking添加请求标头?

时间:2014-03-26 06:55:55

标签: ios iphone afnetworking-2

我想在我的应用程序中使用AFNetworking类与服务器通信。

我是这个图书馆的新手。这是我的代码:

 NSDictionary *user=[[NSDictionary alloc]initWithObjectsAndKeys:@"hiteshp",@"userName",@"12345^",@"password", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer=requestSerializer;   //[AFJSONRequestSerializer serializer];
[manager POST:@"myURL" parameters:user success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@ %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

我想在此请求中添加标头。我试过但它不起作用。如果我写了注释行,那么请求已完成,但我还想再添加一个字段“Authorization”来重新设置。 以及如何打印请求标题?

4 个答案:

答案 0 :(得分:8)

我知道为时已晚,但这里的代码可以满足您的需求

NSString *finalyToken = [[NSString alloc]initWithFormat:@"Bearer %@",user.token];
 AFHTTPRequestOperationManager *manager =
[[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://server1.appscserver.de/api"]];
[manager.requestSerializer setValue:finalyToken forHTTPHeaderField:@"Authorization"];

希望它有助于某人

答案 1 :(得分:5)

在您的代码中使用它:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", nil];

//Authorization    
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:userName password:password];

答案 2 :(得分:2)

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

答案 3 :(得分:0)

在php文件中添加: header('Content-type: application/json');

xcode中的

manager.responseSerializer = [AFJSONResponseSerializer serializer];

示例xcode代码:

NSDictionary *parameters = @{@"key1": @"value1",
                             @"key2": @"value2"};

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    [manager POST:[NSString stringWithFormat:@"http://%@", Url] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);

    }];