本文介绍了如何在C中使用cURL从服务器下载ZIP文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在Linux平台上进行开发。我正在使用 libcurl 并能够接收json响应并将其保存到文件中。以下是代码。
I am developing on Linux platform. I am using libcurl and able to receive json response and saving it to file. Below is the code.
#include <curl/curl.h> #include <curl/types.h> #include <curl/easy.h> #include <string.h> #define URL "www.joes-hardware/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[] = "www.joes-hardware/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 的格式如下所示:
Now I need to fetch a zip file from the server. Suppose the URL is of the format shown below:
#define URL "Server/File.zip"对于此类URL,代码无法保存 zip 文件。
For such URL, the code is not able to save the zip file.
如何实现?
推荐答案我解决了该问题。问题出在HTTPS连接上。我必须为HTTPS添加证书。
I resolved the issue. The problem was with HTTPS connection. I had to add certificates for HTTPS.
基于以下链接:
-
无法使用cURL连接到HTTPS网站。而是返回0个长度的内容
使用CURL从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[] = "example/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 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中使用cURL从服务器下载ZIP文件?
发布评论