首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

iOS 網絡請求實戰:自定義 User-Agent 模擬客戶端類型

     編輯:關於C語言

為什麼要修改 User-Agent?

User-Agent(UA)標識客戶端身份。服務端常根據 UA 返回不同版本頁面(如移動端簡化版 vs PC 完整版)。iOS 原生 UIWebView/WKWebView 默認 UA 包含「iPhone」、「Safari」等標識,有時需偽裝為特定客戶端以獲取適配頁面。

核心實現:NSMutableURLRequest + NSURLSession

// ViewController.m
#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - 點擊觸發網絡請求
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"測試:當前線程 %@", [NSThread currentThread]);

    // 1. 目標 URL
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];

    // 2. 創建可變請求(可修改 Header)
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // 3. 關鍵:設置自定義 User-Agent
    // 模擬 iPhone 正常版 UA 片段
    [request setValue:@"iPhone appleWebKit" forHTTPHeaderField:@"User-Agent"];

    // 4. 異步數據任務(iOS 7+ 推薦 NSURLSession)
    // NSURLConnection 已在 iOS 9 棄用
    [[[NSURLSession sharedSession] dataTaskWithRequest:request
        completionHandler:^(NSData * _Nullable data,
                            NSURLResponse * _Nullable response,
                            NSError * _Nullable error) {

            // 5. 子線程回調:解析數據
            NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

            // 6. 回主線程更新 UI
            dispatch_async(dispatch_get_main_queue(), ^{
                UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
                [webView loadHTMLString:html baseURL:url];
                [self.view addSubview:webView];
            });

        }] resume]; // resume 相當於啟動連接
}

@end

關鍵點深度解析

NSURLSession vs NSURLConnection

  • NSURLSession(iOS 7+):現代網絡 API,支持後台下載、斷點續傳、代理協議豐富,**默認異步**,無同步方法。
  • NSURLConnection:舊 API,iOS 9 起棄用,不再維護。

Completion Handler 執行線程

默認在後台線程(非主隊列)。任何 UI 操作(如創建 WebView、添加子視圖)必須派發到主隊列:

dispatch_async(dispatch_get_main_queue(), ^{ /* UI 代碼 */ });

User-Agent 字符串構成

真實 iPhone Safari UA 示例:

Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)
AppleWebKit/605.1.15 (KHTML, like Gecko)
Version/15.0 Mobile/15E148 Safari/604.1

示例中簡化為 iPhone appleWebKit 僅為演示;生產環境建議完整模擬目標客戶端 UA,避免服務端邏輯判斷失效。

UIWebView 警示

⚠ 棄用警告: UIWebView 自 iOS 12 起棄用,App Store 審核可能拒絕。新項目請使用 WKWebView(需導入 WebKit.framework)。

進階:WKWebView 版本


#import 

@property (nonatomic, strong) WKWebView *webView;

- (void)loadWithCustomUA {
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    [self.view addSubview:self.webView];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"自定義 UA 字符串" forHTTPHeaderField:@"User-Agent"];

    [self.webView loadRequest:request];
}

總結

  1. 使用 NSMutableURLRequest 修改 User-Agent Header。
  2. 採用 NSURLSession 異步請求,回調在子線程,UI 回主線程。
  3. 新項目棄用 UIWebView,改用 WKWebView。
  4. UA 字符串應盡量真實模擬目標客戶端,減少兼容性問題。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved