iPhone應(yīng)用程序 HTTPS服務(wù)器連接教程
iPhone應(yīng)用程序 HTTPS服務(wù)器連接教程是我們要一起來(lái)學(xué)習(xí)的內(nèi)容。你是否也想讓自己的 iPhone 應(yīng)用程序連接 https 服務(wù)器呢?下面我就介紹一下其使用方法。
通常使用 Objective-C 的 NSURLConnection 連接有證明書(shū)的 https 服務(wù)器時(shí)會(huì)出現(xiàn)驗(yàn)證錯(cuò)誤,我們可以使用私有API — setAllowsAnyHTTPSCertificate:forHost 來(lái)解決這個(gè)問(wèn)題。如果是 Cocoa 的應(yīng)用程序應(yīng)該是沒(méi)有什么問(wèn)題,但是用在 iPhone 上,很可能過(guò)不了 App Store 的審查。
所以這里我們使用 libcurl 來(lái)完成在 iphone 上連接 https 服務(wù)器。
準(zhǔn)備
編譯 openssl
連接 https 的前提是要有 OpenSSL。你可以參考 這里 來(lái)為 iPhone 編譯 OpenSSL 靜態(tài)庫(kù)。最終得到下面兩個(gè)靜態(tài)庫(kù)文件。
- libcrypto.a
 - libssl.a
 
編譯 libcurl
接下來(lái)我們下載/編譯 libcurl。下載展開(kāi)后,按照下面配置(根據(jù)實(shí)際情況更改你的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
 
如果***輸出下面的內(nèi)容,說(shuō)明可以編譯支持 https 的 libcurl 了。
- SSL support: enabled (OpenSSL)
 
接下來(lái)
- make
 - make install
 
編譯結(jié)果輸出到 ~/tmp/iphonelib/curl/lib 下的 libcurl.a。
使用
添加到工程中,如圖:

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

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

比如,編譯 libcurl 時(shí)的頭文件的路徑 ~/tmp/iphonelib/curl/include 。
代碼例子下來(lái),讓我們看看在程序中使用 libcurl 的例子。下面的例子在 AppDelegate.m 中實(shí)現(xiàn)。
- #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
 
編譯運(yùn)行,可以用調(diào)試工具得到取得的html,如下圖。

 
在模擬器中使用 libcurl
上面介紹的都是在設(shè)備上運(yùn)行的例子,如果要在模擬器上使用,由于處理器結(jié)構(gòu)不一樣,需要重新編譯 openssl 和 curl 靜態(tài)庫(kù)。編譯的時(shí)候,只要將 SDK 的路徑由 iPhoneOS.platform ⇒ iPhoneSimulator.platform,編譯開(kāi)關(guān) -arch armv6 ⇒ -arch i386 就可以了。只是編譯的文件名***和iphone上用的區(qū)別開(kāi)來(lái),如下所示:
- libcrypto_simulator.a
 - libssl_simulator.a
 - libcurl_simulator.a
 
又或者不改變庫(kù)的名稱,而是增加新的編譯目標(biāo)。
小結(jié):iPhone應(yīng)用程序 HTTPS服務(wù)器連接教程的內(nèi)容介紹我那了,希望本文對(duì)你有所幫助!















 
 
 

 
 
 
 