17 / 01 / 04

给UIWebView加个自定义的User-Agent

//get the user agent NSString *oldAgent = [self.webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; NSLog(@"old agent :%@", oldAgent); NSString *newAgent = [oldAgent stringByAppendingString:@" custom user agent"]; NSLog(@"new agent :%@", newAgent); //regist the new agent NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary]; [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://blog.exgame.club"]]];
  • 补充一下User-Agent的作用:

在http协议里,头信息中有一个 User-Agent,它的作用是告诉服务器,用户客户端是什么浏览器,以及操作系统的信息的。在某些特殊的情况下,服务器根据浏览器的不同类型,输出不 同的内容。大概在三四年前,很多网站都只显示给IE看,所以当时的 opera 浏览器还特别做了一个功能,可以把它的 User-Agent 换成 IE 的。所以 user-agent 是非常不可靠的,原因就是它是客户端自己决定并发送给服务器。