AFNetworking 3.0重定向丢失标头

时间:2017-10-19 13:39:55

标签: ios objective-c afnetworking-3

我在 AFHTTPSessionManager 上使用了 setTaskWillPerformHTTPRedirectionBlock ,但在重定向后,我总是遇到401错误,未提供身份验证凭据。我已经尝试在没有重定向的情况下向端点发送请求,它可以工作。但是通过重定向,似乎重定向后标头丢失了。我也尝试在 AFHTTPSessionManager 块中添加标题,但仍然没有运气。

[self.sessionManager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@", authToken] forHTTPHeaderField:@"Authorization"];
[self.sessionManager.requestSerializer setValue:self.userAgentInfo forHTTPHeaderField:@"User-Agent"];
[self.sessionManager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
    NSLog(@"%@", request.URL);
    return request; 
}];


[self.sessionManager GET:[NSString stringWithFormat:@"%@path/", self.host]
                parameters:nil
                  progress:nil
                   success:^(NSURLSessionTask *task, id responseObject) {

3 个答案:

答案 0 :(得分:0)

您正在使用操作管理器的代码建议,因此您只需设置凭据属性:

self.operationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:...];
self.operationManager.credential = [[NSURLCredential alloc] initWithUser:USERNAME password:PASSWORD persistence:NSURLCredentialPersistencePermanent];

答案 1 :(得分:0)

经过几个小时的努力,找到了解决方案:

[self.sessionManager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@", authToken] forHTTPHeaderField:@"Authorization"];
[self.sessionManager.requestSerializer setValue:self.userAgentInfo forHTTPHeaderField:@"User-Agent"];
[self.sessionManager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
    NSLog(@"%@", request.URL);
    NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:request.URL];
    [newRequest setValue:[NSString stringWithFormat:@"Token %@", authToken] forHTTPHeaderField:@"Authorization"];
    [newRequest setValue:self.userAgentInfo forHTTPHeaderField:@"User-Agent"];
    return newRequest;
}];

[self.sessionManager GET:[NSString stringWithFormat:@"%@paths/", self.host]
                parameters:nil
                  progress:nil
                   success:^(NSURLSessionTask *task, id responseObject) {

答案 2 :(得分:0)

将原始请求的所有http请求标头复制到setTaskWillPerformHTTPRedirectBlock中的新/当前请求中,这对我来说很有用。

在Swift中看起来像那样:

    // copy original request headers to current request when following HTTP redirect
    manager.setTaskWillPerformHTTPRedirectionBlock { (session, task, response, request) -> URLRequest? in
        var newRequest = request
        task.originalRequest?.allHTTPHeaderFields?.forEach({ (arg) in
            let (key, value) = arg
            newRequest.setValue(value, forHTTPHeaderField: key)
        })
        return newRequest
    }