gpt4 book ai didi

c - 如何在 C 中使用 cURL 从服务器下载 ZIP 文件?

转载 作者:太空宇宙 更新时间:2023-11-04 04:41:58 24 4
gpt4 key购买 nike

我在 Linux 平台上开发。我正在使用 libcurl 并且能够接收 json 响应 并将其保存到文件中。下面是代码。

#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include <string.h>

#define URL "http://www.joes-hardware.com/tools.html"
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written;
written = fwrite(ptr, size, nmemb, stream);
return written;
}

int main(void) {
CURL *curl;
FILE *fp;
CURLcode res;
//const char url[] = "http://www.joes-hardware.com/tools.html";

char *url= URL;
char outfilename[FILENAME_MAX] = "./json";
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}

现在我需要从服务器获取一个 zip 文件。假设 URL 的格式如下:

#define URL "https://Server/File.zip"

对于这样的 URL,代码无法保存 zip 文件。

如何实现?

最佳答案

我解决了这个问题。问题出在 HTTPS 连接上。我必须为 HTTPS 添加证书。

基于以下链接:

#define CURL_STATICLIB
#include <stdio.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include <string.h>
#include <stdlib.h>

#define false 0

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written;
written = fwrite(ptr, size, nmemb, stream);
return written;
}

int main(void) {
CURL *curl;
FILE *fp;
CURLcode res;

const char url[] = "https://example.com/filename.zip";
const char outfilename[FILENAME_MAX] = "./json.zip";

curl_version_info_data * vinfo = curl_version_info(CURLVERSION_NOW);

if(vinfo->features & CURL_VERSION_SSL){
printf("CURL: SSL enabled\n");
}else{
printf("CURL: SSL not enabled\n");
}

curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");

/* Setup the https:// verification options. Note we */
/* do this on all requests as there may be a redirect */
/* from http to https and we still want to verify */
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_CAINFO, "./ca-bundle.crt");
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);

curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);

int i=fclose(fp);
if( i==0)
system("unzip -j json.zip");
}
return 0;
}

关于c - 如何在 C 中使用 cURL 从服务器下载 ZIP 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25540547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com