美文网首页iOS开发总结iOS Developer
iOS用libcurl发起一个get请求,并保存返回数据到沙盒

iOS用libcurl发起一个get请求,并保存返回数据到沙盒

作者: Auditore | 来源:发表于2017-07-20 16:46 被阅读215次

    这个需求分为:
    1.如何接入libcurl库,
    2.如何用libcurl发起get请求,
    3.如何将数据保存到沙盒路径下

    一.第一个需求,由于libcurl只有源码,需要你自己去编译各平台下的库,怎么编译参考下我写的另一篇文章:编译支持iOS的libcurl+OpenSSL库(支持https IPv6)
    然后就是引用libcurl.a库了,记得在build phase里面的link binary with ibraries 里面引用libz.tbdlibresolv.tbd这两个系统库

    二.第二个需求,发起请求的方法如下

    bool getUrl(const char *filename,char *url)
    {
        CURL *curl;
        CURLcode res;
        FILE *fp;
        if ((fp = fopen(filename, "wt+")) == NULL){
            // 返回结果用文件存储
            return false;
        }
        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_WRITEDATA, fp);
            res = curl_easy_perform(curl);   // 执行
            NSLog(@"请求返回值是%i",res);
            curl_slist_free_all(headers);
            curl_easy_cleanup(curl);
        }
        fclose(fp);
        return true;
    }
    

    特别提醒, curl_global_init(CURL_GLOBAL_ALL);这个函数是全局初始化函数,只能调用一次,所以最好在didFinishLanuch里面调用,如果在curl_easy_init();之前还未实现,那么libcurl会自动执行一次。所以多线程下最好主动调用该函数以防止在线程中curl_easy_init时多次调用。
    这是因为虽然libcurl是线程安全的,但curl_global_init是不能保证线程安全的,所以不要在每个线程中都调用curl_global_init,didFinishLanuch里调用一次就行了。

    三. 如何上层调用
    由于curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); 这个方法是c的方法,所以传进来的目录filename也要是c String才行,所以上层调用的时候得这么写:

    NSArray *paths =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [paths firstObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"wow.log"];
    getUrl([filePath cStringUsingEncoding:NSUTF8StringEncoding],"https://www.baidu.com");
    

    这样就可以将获取到数据写入到应用的document目录下,保存为wow.log文件。

    四. 对请求的返回值的说明
    也就是对 curl_easy_perform()函数返回值的说明,0表示请求正常返回,详情看下面

    CURLE_OK = 0, 0: no error 
    CURLE_UNSUPPORTED_PROTOCOL, 1: unsupported protocol 
    CURLE_FAILED_INIT, 2: failed init 
    CURLE_URL_MALFORMAT, 3: URL using bad/illegal format or missing URL 
    CURLE_URL_MALFORMAT_USER, 4: unknown error 
    CURLE_COULDNT_RESOLVE_PROXY, 5: couldn't resolve proxy name 
    CURLE_COULDNT_RESOLVE_HOST, 6: couldn't resolve host name 
    CURLE_COULDNT_CONNECT, 7: couldn't connect to server 
    CURLE_FTP_WEIRD_SERVER_REPLY, 8: FTP: weird server reply 
    CURLE_FTP_ACCESS_DENIED, 
    CURLE_FTP_USER_PASSWORD_INCORRECT, 10: unknown error 
    CURLE_FTP_WEIRD_PASS_REPLY, 11: FTP: unknown PASS reply 
    CURLE_FTP_WEIRD_USER_REPLY, 12: FTP: unknown USER reply 
    CURLE_FTP_WEIRD_PASV_REPLY, 13: FTP: unknown PASV reply 
    CURLE_FTP_WEIRD_227_FORMAT, 14: FTP: unknown 227 response format 
    CURLE_FTP_CANT_GET_HOST, 15: FTP: can't figure out the host in the PASV response 
    CURLE_FTP_CANT_RECONNECT, 16: FTP: can't connect to server the response code is unknown 
    CURLE_FTP_COULDNT_SET_BINARY, 17: FTP: couldn't set binary mode 
    CURLE_PARTIAL_FILE, 18: Transferred a partial file 
    CURLE_FTP_COULDNT_RETR_FILE, 19: FTP: couldn't retrieve (RETR failed) the specified file 
    CURLE_FTP_WRITE_ERROR, 20: FTP: the post-transfer acknowledge response was not OK 
    CURLE_FTP_QUOTE_ERROR, 21: FTP: a quote command returned error 
    CURLE_HTTP_RETURNED_ERROR, 22: HTTP response code said error 
    CURLE_WRITE_ERROR, 23: failed writing received data to disk/application 
    CURLE_MALFORMAT_USER, 24: unknown error 
    CURLE_UPLOAD_FAILED, 25: upload failed (at start/before it took off) 
    CURLE_READ_ERROR, 26: failed to open/read local data from file/application 
    CURLE_OUT_OF_MEMORY, 27: out of memory 
    
    CURLE_OPERATION_TIMEOUTED, 28: a timeout was reached 
    CURLE_FTP_COULDNT_SET_ASCII, 29: FTP could not set ASCII mode (TYPE A) 
    CURLE_FTP_PORT_FAILED, 30: FTP command PORT failed 
    CURLE_FTP_COULDNT_USE_REST, 31: FTP command REST failed 
    CURLE_FTP_COULDNT_GET_SIZE, 32: FTP command SIZE failed 
    CURLE_HTTP_RANGE_ERROR, 33: a range was requested but the server did not deliver it 
    CURLE_HTTP_POST_ERROR, 34: internal problem setting up the POST 
    CURLE_SSL_CONNECT_ERROR, 35: SSL connect error 
    CURLE_BAD_DOWNLOAD_RESUME, 36: couldn't resume download 
    CURLE_FILE_COULDNT_READ_FILE, 37: couldn't read a file:// file 
    CURLE_LDAP_CANNOT_BIND, 38: LDAP: cannot bind 
    CURLE_LDAP_SEARCH_FAILED, 39: LDAP: search failed 
    CURLE_LIBRARY_NOT_FOUND, 40: a required shared library was not found
    

    五. 单纯地写一个请求
    如果你不需要写入本地,只是想发起请求,当然也是可以的,简化上面的代码,结果如下

    CURLcode getUrl(char *url)
    {
        CURL *curl;
        CURLcode res = CURLE_OK;
        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);
            res = curl_easy_perform(curl);   // 执行
            NSLog(@"res===%i",res);
            curl_slist_free_all(headers);
            curl_easy_cleanup(curl);
        }
        return res;
    }
    

    调用的话就用getUrl("https://www.baidu.com");
    打完收工

    相关文章

      网友评论

        本文标题:iOS用libcurl发起一个get请求,并保存返回数据到沙盒

        本文链接:https://www.haomeiwen.com/subject/pyqjkxtx.html