ios 下使用curl openssl 下载http或者https文件

时间:2024-05-22 07:27:39

为了保证移动端兼容性的使用
不能使用ios的urlsession
可以使用C语言的curl库来实现下载操作
curl在ios环境下的编译
因为之前编译过openssl 就直接拿过来用了
openssl 是为了增加https支持来使用的
编译通过后使用就非常简单了

使用代码

//
//  ViewController.m
//  libcurlHTTPS
//
//  Created by kai_leedarson on 2018/10/29.
//  Copyright © 2018年 maple_leedarson. All rights reserved.
//

#import "ViewController.h"
#include <curl/curl.h>
#import "JsonDictExchange.h"
@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    curl_version_info_data *data=  curl_version_info(CURLVERSION_NOW);
    printf("\nopenssl version %s\n",data->ssl_version);
}
static int ProgressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
{
    static int pre_percent =0;
    if ( dltotal > -0.1 && dltotal < 0.1 )
        return 0;
    int nPos = (int) ( (dlnow/dltotal)*100 );
    pre_percent = nPos;
    NSLog(@"%d%%",pre_percent);
    return 0;
}

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_VERBOSE, 0L);
        curl_easy_setopt(curl, CURLOPT_URL,url);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_ENABLE_ALPN, 0L);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
        curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, ProgressCallback);
        NSLog(@"请求");
        res = curl_easy_perform(curl);   // 执行
        NSLog(@"请求返回值是%i",res);
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }
    fclose(fp);
    return true;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self testWeb];
}

- (void)testWeb {
    NSString * path0 = [[NSBundle bundleForClass:[self class]] pathForResource:[NSString stringWithUTF8String:"testCloud.json"]  ofType:nil];
    NSData *receiveData = [[NSData alloc] initWithContentsOfFile:path0];
    //获得的json先转换成字符串
    NSString *receiveStr = [[NSString alloc]initWithData:receiveData encoding:NSUTF8StringEncoding];
    //再解析
    NSDictionary *jsonDict = [JsonDictExchange convertJsonWith:receiveStr];
    NSMutableArray  *dataArray = [jsonDict[@"data"] mutableCopy];
    for (NSInteger i=0; i<dataArray.count; i++) {
        NSMutableDictionary *info = [dataArray[i] mutableCopy];
        NSLog(@"开始下载[%ld]url\n%@",(long)i,info[@"url"]);
        NSString *downloadPath = info[@"url"];
        NSArray *array = [info[@"url"] componentsSeparatedByString:@"/"];
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:array.lastObject];
        //6.3 执行剪切操作
        char *charPath1 = (char *)[downloadPath UTF8String];
        char *charPath2 = (char *)[fullPath UTF8String];
        getUrl(charPath2,charPath1);
    }
}


@end

项目结构,记得去掉bitcode 为no 并且加个libz的库

ios 下使用curl openssl 下载http或者https文件

下载效果图片
ios 下使用curl openssl 下载http或者https文件

懒人链接

我只编译了armv7 和arm64的真机版本,需要其他的只能自己编译了

目前还存在没有使用多线程下载来提速的问题。