title: Handling redirects correctly with NSURLConnection
body: <p>For the purposes of this, I'm going to pretend the original url is <code>http://host/form</code> and the new url is <code>https://host/form</code>. (Note that before I ship this, both URLs are going to be secure. However, the nonsecure-to-secure seems like a convenient redirect to test this on.)</p>
  
  <p>I'm accessing a web API using <code>NSURLConnection</code> that redirects me. Basically, I want to take everything I just submitted to <code>http://hostaform</code> and re-submit it to <code>https://host/form</code>. I thought this would be the default behavior, but it looks like the body is being lost in the redirect.</p>
  
  <p>So I think I need to handle the <code>connection:willSendRequest:redirectResponse:</code> event of the <code>NSURLConnection</code>'s delegate and re-attach the body. The problem is this message seems woefully underdocumented. The only info I can find on this method is <strong> NSURLConnection Class Reference</strong>, which isn't very helpful. Among other things, it includes this:</p>
  
  <blockquote><i>redirectResponse</i>: The URL response that caused the redirect. May be nil in cases where this method is not being sent as a result of involving the delegate in redirect processing.</blockquote>
  
  <p>I'm not sure what this means. Combined with an initial <code>willSendRequest:</code> invocation, I think this is means <code>willSendRequest:</code> is being sent even for my initial request, prior to the redirect response. Is that correct?</p>
  
  <p>So I've added code to my delegate to retain the body an extra time, and added this <code>willSendRequest:</code> handler:</p>
  
  <pre><code>- (NSURLRequest *)connection: (NSURLConnection *)inConnection
               willSendRequest: (NSURLRequest *)inRequest
              redirectResponse: (NSURLResponse *)inRedirectResponse;
  {
      if (inRedirectResponse) {
          NSMutableURLRequest *r = [[inRequest mutableCopy] autorelease];
          [r setURL: [inRedirectResponse URL]];
          [r setHTTPBody: body];
          return r;
      } else {
          return inRequest;
      }
  }
  </code></pre>
  
  <p>It doesn't work. But I'm not even sure if this is the right approach. It seems excessively hackish to me. What should I be doing? Is this documented anywhere? I've found nothing useful in Apple's documentation or using Google so far.</p>
  
  <p>(This is on the iPhone, although there doesn't seem to be much difference in these classes.)</p>