How to handle redirecting urls with get parameters

2019-07-01 23:21发布

问题:

I am trying to get an html response from a server(aspx).

NSString *urlstr = [[NSString alloc] initWithFormat:@"http://www.someSiteThatRedirectsWithGetParameters.com?parameter1=1&parameter2=2"];

NSURL *url = [ NSURL URLWithString:urlstr];     
NSMutableURLRequest *urlRequest = [ NSURLRequest requestWithURL: url];

NSData data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

NSURL *lastURL=[response URL];

NSLog(@"Last url %@", lastURL);

I am getting lastURL as www.someSiteThatRedirectsWithGetParameters.com and therefore not getting the html page for the original requested url.

Why is this so and how can I solve this?

EDIT

This is all what I have tried so far : Get the last redirected url in iOS 5? but I am still not able to achieve what I am trying to i.e : get the html page source of the original GET request(going through redirections) having parameters in the url ?

回答1:

I am getting lastURL as www.someSiteThatRedirectsWithGetParameters.com and therefore not getting the html page for the original requested url.

If your request is being redirected, it's because the server to which you're connecting is telling you that there is no page at the URL to which you first made the request, and you should use the redirected URL instead. That's the whole point of a redirect response.

If the response that you get is a HTTP 303, the new request will properly be changed from POST to GET. This is sometimes done to avoid cases where refreshing the page would resubmit the original request with undesirable consequences. In this case, you POST your request to some URL, and the server accepts the request but responds by redirecting the client to a different URL which ultimately displays the server's response.

Why is this so and how can I solve this?

I've explained the 'why' above. The "solution" is to accept the response from the server and follow the redirect to the URL that contains the server's response.



回答2:

I would try the approach of sending two requests. Send the first request, then the redirectURL will be the response. Then make a new URL of the response, sending a request to that url with the GET-parameters. I haven't tried it, but I suppose it could work.