iPhone获得User-Agent(UA)信息的方法

移动开发 iOS
User-Agent(简称UA)是HTTP请求头部用来标识客户端信息的字符串, 包括操作系统, 浏览器等信息. 为了建立手机客户端的信息数据库, 需要从手机的http请求中取到这一字符串.

如果你需要获取Android手机的UA信息,请移步这里Android获得UA信息的方法

iPhone中取到UA信息的方法如下:

1.利用浏览器控件UIWebView建立一个http请求

2.在请求建立的期间, 建立一个新的事件循环用来判断UA信息是否已经建立

3.在发送http请求之前截获UA信息, 并且取消这一http请求 ;)

获取iPhone UA的代码如下:

  1. UIWebView *_webView; 
  2. NSString *userAgent; 
  3.  
  4. - (void)createHttpRequest { 
  5.     _webView = [[UIWebView alloc] init]; 
  6.     _webView.delegate = self; 
  7.     [_webView loadRequest:[NSURLRequest requestWithURL: 
  8.     [NSURL URLWithString:@"http://www.eoe.cn"]]]; 
  9.     NSLog(@"%@", [self userAgentString]); 
  10.     [_webView release]; 
  11.  
  12. -(NSString *)userAgentString 
  13.     while (self.userAgent == nil)  
  14.     { 
  15.         NSLog(@"%@", @"in while"); 
  16.         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; 
  17.         } 
  18.     return self.userAgent; 
  19.  
  20. -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 
  21.     if (webView == _webView) { 
  22.     self.userAgent = [request valueForHTTPHeaderField:@"User-Agent"]; 
  23.     // Return no, we don't care about executing an actual request. 
  24.     return NO; 
  25.     return YES; 
  26.  
  27. - (void)dealloc { 
  28. [userAgent release]; 
  29.     [super dealloc]; 
  30.   

程序在iPhone4.1模拟器中运行结果如下:

2010-12-21 12:52:38.302 UATest[6722:207] in while

2010-12-21 12:52:38.305 UATest[6722:207] in while

2010-12-21 12:52:38.307 UATest[6722:207] in while

2010-12-21 12:52:38.307 UATest[6722:207] in while

2010-12-21 12:52:38.308 UATest[6722:207] in while

2010-12-21 12:52:38.309 UATest[6722:207] in while

2010-12-21 12:52:38.312 UATest[6722:207] Mozilla/5.0 (iPhone Simulator; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/8B117

责任编辑:张叶青 来源: eoe Android开发者社区
相关推荐

2021-12-28 07:20:44

UA网络协议

2009-03-27 14:40:38

AndroidiPhoneFlash

2011-12-13 14:19:32

iPhone信息图

2017-10-25 14:44:37

PackageManaApp信息

2013-08-21 11:31:21

iPhone图片方法

2019-02-12 09:10:53

2018-05-11 09:17:57

CIO

2009-08-25 09:40:05

思科网络认证证书思科网络认证

2022-05-11 11:26:14

乌克兰恶意链接化学攻击

2012-04-11 16:56:55

苹果

2023-11-29 13:54:00

ChatGPT模型

2012-04-26 13:17:56

iPhone应用发布登录银行信息

2011-03-29 10:22:35

Zabbix Agen安装

2011-03-29 14:37:47

Zabbix Agen配置

2011-07-20 15:42:18

iPhone 划动条

2011-08-05 16:58:25

iPad iPhone UIImagePic

2009-11-07 19:09:35

Windows 7优惠

2010-01-08 14:29:58

华为交换机snmp

2021-08-30 11:07:32

iPhone存储空间

2011-08-03 17:27:40

iPhone UIScrollVi
点赞
收藏

51CTO技术栈公众号