iOS 使用 libcurl
libcurl 是用C語言寫的一套 開源 庫,是為網路客戶端提供資料傳輸功能的函式庫。
libcurl 支援 SMTP、HTTP、HTTPS、FTP、TELNET 等協議和各種 SSL 安全認證,支援 Solaris, NetBSD, FreeBSD, OpenBSD, Darwin, HPUX, IRIX, AIX, Tru64, Linux, UnixWare, HURD, Windows, Amiga, OS/2, BeOs, Mac OS X, Ultrix, QNX, OpenVMS, RISC OS, Novell NetWare, DOS 等平臺,在 Android 和 iOS 上面也可以使用 libcurl 這個庫。
下面是官網的英文簡介:
libcurl is a free and easy-to-use client-side URL transfer library, supporting DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos), file transfer resume, http proxy tunneling and more! libcurl is highly portable, it builds and works identically on numerous platforms, including Solaris, NetBSD, FreeBSD, OpenBSD, Darwin, HPUX, IRIX, AIX, Tru64, Linux, UnixWare, HURD, Windows, Amiga, OS/2, BeOs, Mac OS X, Ultrix, QNX, OpenVMS, RISC OS, Novell NetWare, DOS and more... libcurl is free, thread-safe, IPv6 compatible, feature rich, well supported, fast, thoroughly documented and is already used by many known, big and successful companies.
分享內容
今天跟大家分享 libcurl 在 iOS 上面如何使用,主要分享內容如下:
1、iOS 工程整合 libcurl以及整合注意事項。
2、利用 libcurl 傳送 HTTP GET 和 POST 請求。
3、使用 springboot 搭建本地服務,這個只是為了演示不是分享的重點。
搭建本地服務
本地服務採用 Spring Boot
開發,開發語言是 Java
,JDK 版本1.8, Spring Boot
版本是 v2.1.3.RELEASE
,整合 Web
元件即可,比較簡單。關於如何搭建 Spring Boot
的開發環境,大家自行搜尋解決,也可以直接使用我的 git 工程, 猛戳前往 即可獲取完整程式碼示例。
工程結構如下圖所示:

關鍵程式碼如下:

該工程只是為了配合 libcurl 的使用而誕生的,沒有什麼難度。
整合 libcurl
1、新建 iOS 工程
這裡工程為 tutorial_libcurl_iOS
。
2、準備庫檔案、標頭檔案
libcurl 可以自己編譯,也可以使用別人編譯好的二進位制檔案。我使用的是 curl-android-ios 這個工程裡面編譯好的檔案。
3、給工程 tutorial_libcurl_iOS
新增庫和標頭檔案
將上面的檔案拷貝至工程目錄即可,現在工程目錄如下:

4、設定路徑
在 xcode 中 Building Settings
找到 User Header Search Paths
為如下內容:
$(SRCROOT)/tutorial_libcurl_iOS/Classes
這一步不是必須的,我個人比較喜歡這樣整理和設定目錄。
5、新增 libz.tbd
如果不新增這個庫,編譯無法通過,會顯示如下錯誤:

傳送 HTTP 請求
下面說一下如何使用 libcurl 來發送 HTTP 的 GET 和 POST 請求。只給出核心示例程式碼,其餘的大家去 tutorial_libcurl 獲取完整示例程式碼,包括 Spring Boot
的。
ViewController.m
#import"ViewController.h" #import"curl/curl.h" // 我本機的 IP 和埠,實際你要換成你自己的 #define HOST_URL @"http://172.20.10.2:8080/user" @interface ViewController() @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (IBAction)doHTTPGETToFileAction:(id)sender { NSString *reqUrl = [NSString stringWithFormat:@"%@%@", HOST_URL, @"?id=1&name=veryitman"]; const char *url = [reqUrl cStringUsingEncoding:NSUTF8StringEncoding]; http_get_req(url); } - (IBAction)doHTTPPOSTToFileAction:(id)sender { const char *url = [HOST_URL cStringUsingEncoding:NSUTF8StringEncoding]; const char *data = "id=2&name=veryitman"; http_post_req(url, data); } #pragma mark - C void http_get_req(const char *url) { CURL *curl; const char *fpath = rspDataPath(@"http_get_rsp_data.log"); FILE *fp; fp = fopen(fpath, "wt+"); struct curl_slist *headers = NULL; //增加HTTP header headers = curl_slist_append(headers, "Accept:application/json"); headers = curl_slist_append(headers, "Content-Type:application/json"); headers = curl_slist_append(headers, "charset:utf-8"); //初始化 curl = curl_easy_init(); if (curl) { //改協議頭 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POST, url); //wt+:讀寫開啟或著建立一個文字檔案;允許讀寫 if (NULL != fp) { // 請求結果寫入到檔案當中 curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); } CURLcode rsp_code = curl_easy_perform(curl); if (CURLE_OK == rsp_code) { NSLog(@"請求返回成功"); } else { NSLog(@"請求返回失敗,返回碼是 %i", rsp_code); } curl_slist_free_all(headers); curl_easy_cleanup(curl); } fclose(fp); } void http_post_req(const char *url, const char *req_data) { const char *fpath = rspDataPath(@"http_post_rsp_data.log"); FILE *fp; fp = fopen(fpath, "wt+"); CURL *curl; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url); NSLog(@"length: %ld", strlen(req_data)); /* size of the POST data */ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(req_data) + 1); /* pass in a pointer to the data - libcurl will not copy */ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req_data); if (NULL != fp) { // 請求結果寫入到檔案當中 curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); } CURLcode rsp_code = curl_easy_perform(curl); if (CURLE_OK == rsp_code) { NSLog(@"請求返回成功"); } else { NSLog(@"請求返回失敗,返回碼是 %i", rsp_code); } curl_easy_cleanup(curl); } fclose(fp); } @end
啟動 Spring Boot 專案,啟動成功後,再執行 xcode 工程,可以測試。
點選對應的按鈕就可以傳送 GET 和 POST 請求了。
請求返回的結果被寫入到了沙盒檔案中,可以在終端使用 cat
命令檢視對應的響應結果。
GET 響應結果:
cat ~/Library/Developer/CoreSimulator/Devices/BA882AC3-7977-49C7-8B0D-65EFD1541B68/data/Containers/Data/Application/3A21CFC5-3044-4FC0-9BFA-B311A59187AF/Documents/http_get_rsp_data.log
user info: id=2 name=veryitman
POST 響應結果:
cat ~/Library/Developer/CoreSimulator/Devices/BA882AC3-7977-49C7-8B0D-65EFD1541B68/data/Containers/Data/Application/86E7D457-97B1-4D8C-80D5-E8179B691F76/Documents/http_post_rsp_data.log
user info: id=2 name=veryitman
後續為大家分享如何使用回撥來接收 HTTP 響應資料、其他網路請求的情況以及 Android 上面如何使用 libcurl 庫。
掃碼關注,期待與你的交流~