我正在使用libcurl
并能够receive json response
和saving it to file
。
以下是代码
#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;
//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"
对于此类网址,代码无法保存zip
文件。
怎么做到这一点?
我正在为LINUX
平台开发。
答案 0 :(得分:0)
解决了问题。问题出在HTTPS connection
已添加certificate
基于以下链接:
Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?
Getting no content from a HTTPS connection using CURL
#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;
//char *url = "http://www.joes-hardware.com/tools.html";
char *url= "https://HOST/FileName.zip";
//char *url= "https://wordpress.org/";
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");
curl_easy_setopt(curl, CURLOPT_URL, url);
/* 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_SSL_VERIFYPEER, 1);
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;
}