iPhone應用程序 HTTPS服務器連接教程
iPhone應用程序 HTTPS服務器連接教程是我們要一起來學習的內容。你是否也想讓自己的 iPhone 應用程序連接 https 服務器呢?下面我就介紹一下其使用方法。
通常使用 Objective-C 的 NSURLConnection 連接有證明書的 https 服務器時會出現驗證錯誤,我們可以使用私有API — setAllowsAnyHTTPSCertificate:forHost 來解決這個問題。如果是 Cocoa 的應用程序應該是沒有什么問題,但是用在 iPhone 上,很可能過不了 App Store 的審查。
所以這里我們使用 libcurl 來完成在 iphone 上連接 https 服務器。
準備
編譯 openssl
連接 https 的前提是要有 OpenSSL。你可以參考 這里 來為 iPhone 編譯 OpenSSL 靜態庫。最終得到下面兩個靜態庫文件。
- libcrypto.a
- libssl.a
編譯 libcurl
接下來我們下載/編譯 libcurl。下載展開后,按照下面配置(根據實際情況更改你的SDK目錄,版本)。
- ./configure --prefix=$HOME/tmp/iphonelib/curl \
- --host=arm-apple-darwin --disable-shared --with-random=/dev/urandom \
- CC=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc \
- CFLAGS="-arch armv6 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/
- iPhoneOS3.0.sdk -I$HOME/tmp/iphonelib/openssl/include -L$HOME/tmp/iphonelib/openssl/lib" \
- CPP=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/cpp \
- AR=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/ar
如果***輸出下面的內容,說明可以編譯支持 https 的 libcurl 了。
- SSL support: enabled (OpenSSL)
接下來
- make
- make install
編譯結果輸出到 ~/tmp/iphonelib/curl/lib 下的 libcurl.a。
使用
添加到工程中,如圖:

如下圖所示,將編譯好的靜態庫拖到你的工程中:
另外,由于 openssl 中使用了 zlib,所以還需要在工程中加入鏈接開關。(該庫被包含在iPhone中,不需要重新編譯)
如下圖所示,在連接中追加 -lz。如圖:

***,如下圖添加編譯所需的頭文件路徑。如圖:

比如,編譯 libcurl 時的頭文件的路徑 ~/tmp/iphonelib/curl/include 。
代碼例子下來,讓我們看看在程序中使用 libcurl 的例子。下面的例子在 AppDelegate.m 中實現。
- #import "AppDelegate.h"
- #include <curl/curl.h>
- @implementation AppDelegate
- -(void)applicationDidFinishLaunching:(UIApplication *)application {
- window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
- // Override point for customization after application launch
- [window makeKeyAndVisible];
- CURL *curl;
- CURLcode res;
- curl = curl_easy_init();
- if (curl) {
- curl_easy_setopt(curl, CURLOPT_URL, "https://twitter.com/");
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
- res = curl_easy_perform(curl);
- if (0 != res) {
- fprintf(stderr, "curl error: %d\n", res);
- }
- curl_easy_cleanup(curl);
- }
- }
- -(void)dealloc {
- [window release];
- [super dealloc];
- }
- @end
編譯運行,可以用調試工具得到取得的html,如下圖。

在模擬器中使用 libcurl
上面介紹的都是在設備上運行的例子,如果要在模擬器上使用,由于處理器結構不一樣,需要重新編譯 openssl 和 curl 靜態庫。編譯的時候,只要將 SDK 的路徑由 iPhoneOS.platform ⇒ iPhoneSimulator.platform,編譯開關 -arch armv6 ⇒ -arch i386 就可以了。只是編譯的文件名***和iphone上用的區別開來,如下所示:
- libcrypto_simulator.a
- libssl_simulator.a
- libcurl_simulator.a
又或者不改變庫的名稱,而是增加新的編譯目標。
小結:iPhone應用程序 HTTPS服務器連接教程的內容介紹我那了,希望本文對你有所幫助!



















