2012-05-05 56 views

回答

3

短网址的HTTP重定向的工作。您可以使用短网址请求设置NSURLConnection并设置代理。在委托,实施方法:

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response; 

如果response是非nil,这是一个重定向。您可以检查响应。您可以使用-isKindOfClass:来检查它是否为NSHTTPURLResponse的实例,然后从中获取其他数据。

此外,您还可以检查新requestNSURLConnection建议。它的URL属性将是服务器重定向您的连接请求的新URL。

如果您被重定向并且您有理由相信您不会被重定向,并且您完全感兴趣,那么您可以通过在连接对象上调用-cancel来取消连接请求。


更新。下面是一些示例代码:

#import <Foundation/Foundation.h> 

static BOOL stop; 

@interface MyDelegate : NSObject 
@end 

@implementation MyDelegate 

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response 
{ 
    NSLog(@"request %@", request); 
    NSLog(@"response %@", response); 
    return response ? nil : request; 
} 

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"%s: error %@", __func__, error); 
    stop = TRUE; 
} 

- (void) connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSLog(@"%s", __func__); 
    stop = TRUE; 
} 

@end 

int main (int argc, const char * argv[]) { 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

    NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://tinysong.com/HJ9h"]]; 
    MyDelegate* del = [[MyDelegate alloc] init]; 
    [NSURLConnection connectionWithRequest:req delegate:del]; 
    while (!stop) 
     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; 

    [pool drain]; 
    return 0; 
} 

产生这样的输出:

request <NSURLRequest http://tinysong.com/HJ9h> 
response (null) 
request <NSURLRequest http://grooveshark.com/#!/s/~/3Xl6OQ?src=11> 
response <NSHTTPURLResponse: 0x103500340> 
-[MyDelegate connectionDidFinishLoading:] 
+0

我试过使用它,该方法是完美的工作。但我有一个问题。在该方法里面检索url的命令是什么?示例代码会很好。谢谢 –

+0

这应该提供新的URL:'[请求URL]'。 –

+0

我尝试过,但它继续给我http://tinysong.com/HJ9h –

0

一个简单的方法来做到这一点从终端

curl --head shorturl 

这将只显示短头,你可以看到在那里的网址。

例如

$ curl --head http://tinysong.com/HJ9h 
HTTP/1.1 301 Moved Permanenty 
Server: sharkattack! 
Date: Sat, 05 May 2012 22:13:10 GMT 
Content-Type: text/html; charset=UTF-8 
Connection: close 
Set-Cookie: TinysongSessionID=4518ef13c93199344a23bb9fe9af3e98; expires=Sat, 02-May-2015 22:13:10 GMT; path=/ 
Location: http://grooveshark.com/#!/s/~/3Xl6OQ?src=11 
Cache-Control: max-age=300 
Expires: Sat, 05 May 2012 22:18:10 GMT 
Vary: Accept-Encoding 
X-Hostname: rhl082 
X-N-Hostname: RHL082 

而且你可以看到它指向的是在Location领域的网址。

因此,使用这种带有NSTask会给你一个结果字符串,你可以工作。

0

提供该服务使用HTTP 301,302一个303重定向你可以做一个HTTP请求到初始网址...

如果响应头返回301,302或303重新再作要求在指定的新位置header ...然后你会重复这个,直到状态码是别的东西,比如200 ...

然后你可以从响应头和volatile读取主机和路径,你有你的长URL ..

现在获得头方面......我用ASIHTTPRequest为我所有的网络需求...http://allseeing-i.com/ASIHTTPRequest/How-to-use它有一个选项来跟随重定向,所以我认为如果你提出请求,你将能够读取ResponseHeaders并获得长URL。

希望有所裨益