2012-11-22 61 views
3

我有一個URL.when我嘗試在瀏覽器中打開它,它會重定向到另一個URL &顯示內容。我想要那個內容但是我沒有得到那個重定向的URL。所以,我無法顯示數據。如何獲取重定向的URL

我該如何編程?

例如我所網址:http://www.windpowerengineering.com/?p=11020

&重定向的URL是:http://www.windpowerengineering.com/design/mechanical/blades/bladeless-turbine-converts-wind-into-fluid-power/

我想這個重定向的URL。我怎麼能得到這個?

回答

4

1)指定類符合UIWebViewDelegate協議(並確保您的WebView委託出口連接到您的視圖控制器) :

@interface YourWebsiteViewController : UIViewController <UIWebViewDelegate> 

2)添加以下委託方法:

-(void)webViewDidStartLoad:(UIWebView *)webView 
{ 
    NSURL *url = [webView.request mainDocumentURL]; 
    NSLog(@"The Redirected URL is: %@", url); 
} 

取決於你想用這些信息做什麼,你可能要替換#2這個方法(這將讓您有機會阻止加載一個頁面):

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 
{ 
    NSURL *url = [request mainDocumentURL]; 
    NSLog(@"The Redirected URL is: %@", url); 
    // Return YES if you want to load the page, and NO if you don't. 
    return NO; 
} 
+0

是的,它的工作,但我想在網絡視圖之前獲取重定向url **加載**和顯示。 – user1673099

+0

@ user1673099我編輯了回覆。 –

+0

是的,太棒了!非常感謝!再次感謝! – user1673099

0

採用javascript

document.referrer 
0

即URL是http頭的一部分。這就是發生的事情:

請求1:http://www.windpowerengineering.com/?p=11020

迴應1:頁面已經搬到轉到http://www.windpowerengineering.com/design/mechanical/blades/bladeless-turbine-converts-wind-into-fluid-power/

,然後你的瀏覽器會去:

請求2:http://www.windpowerengineering.com/design/mechanical/blades/bladeless-turbine-converts-wind-into-fluid-power/

響應3:這裏是html

如果你看看http頭響應1,您將能夠從Location標題中提取網址。在Objective C中,這是做到這一點的一種方法:

NSURLResponse* response = // the response, from somewhere 
NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields]; 
NSString* redirection_url = [headers objectForKey:@"Location"]; 

在上面的代碼,你可以訪問所有的響應HTTP頭從headers字典。

+0

我怎樣才能得到位置標題編程 – user1673099

+0

@ user1673099,我更新了我的迴應。 – Roman

+0

你能幫我一些代碼,因爲我沒有得到你的觀點,比如如何得到請求的迴應1 – user1673099

0

你試過這種委託方法嗎?

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ 

只要webview加載網頁,它就會被調用。

你可以從這個方法的參數之一的URL,request

NSURL *regURL=[request URL]; 
NSString *urlString=[regURL absoluteString]; 
+0

我得到了urlString作爲about:blank – user1673099