我有一个格式为schema:// hostname的URL(例如https://some.server.com)。
我正在尝试获取重定向页面(以我的情况为登录表单)(例如,httpx://some.server.com/this/is/you/loginpage)
浏览器将自动重定向到此页面,该页面通过响应中的“ Location”标头从服务器接收。在Google Chrome浏览器中分析此请求时,我看到带有位置标头的“ 302”状态。此位置标头具有正确的URL,但是由于某些原因,我无法使用NSURLConnectionDelegate方法检索此标头(或http状态!)。我也尝试过AFNetworking,但结果相同。
在这种情况下,仅对规范更改而不对位置更改调用connection:willSendRequest:redirectResponse:方法。
我还发现UIWebView DOES会自动重定向到此“位置” URL。我还可以使用UIWebView委托方法捕获此重定向:webView:shouldStartLoadWithRequest:navigationType:我不想使用UIWebView,因为这是一个UI组件,只能在主线程中访问,而我正在做一些事情后台操作。(但是,现在我将其用作解决方法)。
此处还描述了所需的行为:http : //en.wikipedia.org/wiki/HTTP_location有任何想法如何使用NSURLConnection(或任何AFNetworking类)检测/执行此重定向?
使用NSURLConnection的相关代码(在这种情况下不会重定向):
- (void)resolveUsingNSURLConnection:(NSURL *)URL {
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
self.isRequestBusy = YES;
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (urlConnection) {
[self waitUntilRequestFinished];
}
NSLog(@"resolveUsingNSURLConnection ready (status: %i, URL: %@)", self.response.statusCode, self.response.URL);
}
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse {
if (redirectResponse) {
// Just log the redirect request
NSLog(@"[%@] server redirect allowed:\n\t%@ %@\n\t%@ %@", NSStringFromClass([self class]), self.request.HTTPMethod, self.request.URL.absoluteString, request.HTTPMethod, request.URL.absoluteString);
return request;
} else {
// Just log the canonical change
NSLog(@"[%@] canonical change:\n\t%@ %@\n\t%@ %@", NSStringFromClass([self class]), self.request.HTTPMethod, self.request.URL.absoluteString, request.HTTPMethod, request.URL.absoluteString);
return request;
}
}
使用UIWebView的相关代码(具有所需的重定向行为,而不是所需的组件):
- (void)resolveUsingUIWebView:(NSURL *)URL {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(resolveUsingUIWebView:) withObject:URL waitUntilDone:YES];
return;
}
NSURLRequest *hostnameURLRequest = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
self.isRequestBusy = YES;
UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectZero];
webview.delegate = self;
[webview loadRequest:hostnameURLRequest];
[self waitUntilRequestFinished];
NSLog(@"resolveUsingUIWebView ready (status: UNKNOWN, URL: %@)", webview.request.URL);
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"webView:shouldStartLoadWithRequest: %@ (%i)", request.URL, navigationType);
return YES;
}
我见过几种UIWebView处理重定向的方法,有两种:
Web服务可能会检查User-Agent字符串并采取不同的行动。
重定向可以是JaveScript。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句