UA在項目中的應用android
給項目的webview或項目中的接口請求加一個區分,用來區別是iOS端訪問、android訪問仍是在瀏覽器訪問的,這時須要添加User Agent (http請求 header中的一個參數)web
2)webview全局的設置兩種方法:瀏覽器
//1.直接在app delegate 裏面設置(這種方法比較簡單,其中具體的參數本身選擇性的設置) - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //修改app默認UA UIWebView* tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero]; NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; // NSLog(@"------%@",userAgent); NSString *executableFile = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey]; NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey]; NSString *ua = [NSString stringWithFormat:@"%@ %@/%@", userAgent, executableFile,version]; // NSLog(@"------%@",ua); [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : ua, @"User-Agent" : ua}]; return YES; } // 2.第二種方法 //在webView:shouldStartLoadWithRequest:navigationType:方法中同步加載到request的data,而後使用UIWebView的-loadData:MIMEType:textEncodingName:baseURL:方法加載data - (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (...) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSHTTPURLResponse *response = nil; NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (error) { // ... } dispatch_async(dispatch_get_main_queue(), ^{ [self.webView loadData:data MIMEType:response.MIMEType textEncodingName:response.textEncodingName baseURL:request.URL]; }); }); return NO; } return YES; }
3) 通常的網絡請求在request 網絡
// AFN中 在 AFHTTPRequestSerializer 類中 //調用- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString*)field; 給請求頭設置參數 @"User-Agent" 的值