title: iOS HTTP Post Redirection Handler Not Working
body: <p>I am new to iOS development. I was just trying to do a post request to a server, but encountered problems mentioned <a href="https://stackoverflow.com/questions/1446509/handling-redirects-correctly-with-nsurlconnection">here</a> with server redirection. I used the event handler mentioned in the answer, but things still do not work right. </p>
  
  <p>Here is my .m code: </p>
  
  <pre><code>@interface ViewController ()
  
  @end
  
  @implementation ViewController
  
  
  #pragma mark NSURLConnection Delegate Methods
  
  
  //CALL BACK METHODS
  
  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
      NSLog(@"    didReceiveResponse");
      // A response has been received, this is where we initialize the instance var you created
      // so that we can append data to it in the didReceiveData method
      // Furthermore, this method is called each time there is a redirect so reinitializing it
      // also serves to clear it
  
  
      //initialize response
      _responseData = [[NSMutableData alloc] init];
  
  }
  
  - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
      NSLog(@"   didReceiveData");
      // Append the new data to the instance variable you declared
      [_responseData appendData:data];
  
  
  
  }
  
  - (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                    willCacheResponse:(NSCachedURLResponse*)cachedResponse {
      // Return nil to indicate not necessary to store a cached response for this connection
      return nil;
  }
  
  
  
  
  - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
      NSLog(@"   connectionDidFinishLoading ");
  
      // The request is complete and data has been received
      // You can parse the stuff in your instance variable now
  
      NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
      NSLog(@"    async response data: %@", dataReceived);
  
  
  
  }
  
  - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
      NSLog(@"   didFailWithError");
  
      // The request has failed for some reason!
      // Check the error var
  }
  
  
  
  - (void)didReceiveMemoryWarning
  {
      [super didReceiveMemoryWarning];
      // Dispose of any resources that can be recreated.
  }
  
  - (void)viewDidLoad
  {
      [super viewDidLoad];
      // Do any additional setup after loading the view, typically from a nib.
  
  
      NSString *post = [NSString stringWithFormat:@"&amp;j_username=%@&amp;j_password=%@",@"usrname",@"pw"];
      NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  
      NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
  
      request = [[NSMutableURLRequest alloc] init];
      request.HTTPMethod= @"POST";
      //parameters
      [request setURL:[NSURL URLWithString:@"url"]];
      [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
      [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
      [request setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
      [request setHTTPBody:postData];
  
  
  
  
      // Send a synchronous request
      if (0) {
          NSURLResponse * response = nil;
          NSError * error = nil;
          NSData * data = [NSURLConnection sendSynchronousRequest:request
                                                returningResponse:&amp;response
                                                            error:&amp;error];
          NSLog(@"  Synchronous request done");
          if (error == nil)
          {
              // Parse data here
              NSLog(@"     Synchronous response has no error");
              NSLog(@"    Synchronous Reply: %@", response);
          }
      }
      else {
          // Send Asynchronous request
          //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
          [NSURLConnection connectionWithRequest:request delegate:self];
          NSLog(@"  Asynchronous request sent");
      }
  
  
  
  }
  
  - (NSURLRequest *)connection: (NSURLConnection *)connection
               willSendRequest: (NSURLRequest *)inRequest
              redirectResponse: (NSURLResponse *)redirectResponse;
  {
      if (redirectResponse) {
          // we don't use the new request built for us, except for the URL
          NSURL *newURL = [request URL];
          NSString *redirectURL= [newURL absoluteString];
          NSLog(@"Redirect URL: ");
          NSLog(redirectURL);
          // Previously, store the original request in _originalRequest.
          // We rely on that here!
          NSMutableURLRequest *newRequest = [request mutableCopy];
          [newRequest setURL: newURL];
          NSLog(@"redirect occur");
          return newRequest;
      } else {
          NSLog(@"no redirect");
          return inRequest;
      }
  }
  
  @end
  </code></pre>
  
  <p>Without the handler, the request goes through fine(just without the body attached); but with the handler, the redirection gets detected again and again b/c the redirected url is same as the original. Eventually the requested died because of too many redirects. I think this might be a server end problem, but am I doing anything wrong in the coding that causes this? </p>