NSURLRequest with User-Agent

关于iOS上的http请求还在不断学习,从早先的时候发现原来iOS的http请求可以自动保存cookie到后来的,发现ASIHttpRequest会有User-Agent,到现在发现竟然NSURLRequest默认不带USer-Agent的。添加方法:

#define USERAGENT @"Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3"
NSMutableURLRequest *restRequest = [NSMutableURLRequest requestWithURL:url
    cachePolicy:NSURLRequestReloadIgnoringCacheData
    timeoutInterval:30.0];
[restRequest setValue:USERAGENT forHTTPHeaderField:@"User-Agent"];

而我的情况要稍微复杂一点,发现服务器对于我请求的URL竟然进行了跳转,还需要再实现一个代理:

-(NSURLRequest *)connection:(NSURLConnection*)connection
    willSendRequest:(NSURLRequest*)request
    redirectResponse:(NSURLResponse*)redirectResponse{
    NSMutableURLRequest *newReq = [request mutableCopy];
    [newReq setValue:USERAGENT forHTTPHeaderField:@"User-Agent"];
    return [newReq autorelease];
}

that’s all

参考资料:
NSMutableURLRequest and user-agents

转载请注明: 转自Rainbird的个人博客
   本文链接: NSURLRequest with User-Agent


相关博文

    分享到:

About rainbird

IOS攻城狮
This entry was posted in IOS开发, Mac开发 and tagged , , , , , . Bookmark the permalink.

发表评论