Search code examples
iosxcodehttp-redirectafnetworkingafnetworking-2

AFNetworking change redirect request from GET to POST


So, I am switching from using ASI library to AFNetworking and I am running into an issue with redirect request. Here is the code I am using:

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:originalRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    debugLog(@"SM Success, Redirect URL: %@",[[[operation response] URL] absoluteString]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    debugLog(@"SM Fail: %@", error);
}];

[operation setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) {

    if (redirectResponse) {
        debugLog(@"REDIRECT URL: @%", [request URL]);
        NSMutableURLRequest *r = [originalRequest mutableCopy];
        [r setURL: [request URL]];
        return r;
    } else {
        debugLog(@"Redirecting to : %@", [request URL]);
        return request;
    }        
}];

What I want to do, is to change redirect request from GET to POST. In ASI, I explicitly suppressed all redirects and once I received 302 status, I would create a new request and send it as POST. Is this the same thing I should do with AFNetworking?


Solution

  • When you copy the original request you are using the same HTTP method, if you want to change from GET to POST you should do:

    NSMutableURLRequest *r = [originalRequest mutableCopy];
    [r setHTTPMethod:@"POST"];
    [r setURL: [request URL]];
    return r;