NSURLRequest with UserAgent

关于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

 
 
posted @ 2015-03-06 16:15  ygm900  阅读(1554)  评论(0编辑  收藏  举报