User-Agent not changing in NSMutableURLRequest

痴心易碎 提交于 2019-12-13 12:29:09

问题


I know there may be several issues about this, but i´m facing a problem when i try to set a new "user agent" for my UIWebView. Here is what i am doing right now:

NSURL *myUrl = [NSURL URLWithString:auxUrl];
    NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:myUrl];

    NSMutableString *auxUserAgent = [[NSMutableString alloc] initWithString:[myRequest valueForHTTPHeaderField: @"User-Agent"]];
    [auxUserAgent appendString:@"(iOS)"];

    [myRequest setValue:auxUserAgent forHTTPHeaderField:@"User-Agent"];

    NSLog(@"UA : %@",[myRequest valueForHTTPHeaderField: @"User-Agent"]);

I am trying to append some text to the actual user agent, and in the XCode console it does show the new user agent value.

2013-12-16 19:03:42.200 App[736:60b] UA : Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/11B554a(iOS)

But when i run my App, it shows the old one. Here is a screenshot of the user agent shown in the web page i am showing in the UIWebView:

So.. my questions are: What am i missing?? is there something in the system that doesn´t allow developers to change this data??

Thank you.


回答1:


I "solved" my problem by putting in the didFinishLaunchingWithOptions of my AppDelegate.m the following code:

 NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@"YOUR CUSTOM USER-AGENT", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

The thing is that i cannot append the text to the user agent itself, but i can write the data i need to differentiate between the access to the web page from the different apps or web browsers.

Thank you all for your help.




回答2:


It won't work like that. UIWebView overrides the User-Agent field.

If you try to log the User-Agent in the webView:shouldStartLoadWithRequest:navigationType: method, you'll see that it's already overridden, however you can use NSURLConnection to load your request with a custom User-Agent and then use the loadHTMLString:baseURL: method or loadData:MIMEType:textEncodingName:baseURL: method from UIWebView to display the downloaded data from NSURLConnection.



来源:https://stackoverflow.com/questions/20617960/user-agent-not-changing-in-nsmutableurlrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!