Libcurl study notes (2)-download files via HTTP protocol

1. Introduction

The main function of libcurl is to use different protocols to connect and communicate with different servers ~ that is, quite encapsulated sockPHP supports libcurl (allowing you to connect and communicate with different servers using different protocols). libcurl currently supports http, https, ftp, gopher, telnet, dict, file, and ldap protocols. Libcurl also supports HTTPS certificate authorization, HTTP POST, HTTP PUT, FTP upload (of course you can also use PHP's ftp extension), HTTP basic form upload, proxy, cookies, and user authentication.

2. API description

The libcurl API

2.1 curl_easy_init

Initiate a curl session

2.2 curl_easy_setopt

Set an option for the curl call

2.4 curl_easy_perform

Perform a curl session

2.5 curl_easy_cleanup

Close a curl session

Three, example

#include <stdio.h>
#include <curl/curl.h>

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

int main(void) 
{
    
    
    char fileName[30] = "app.zip";
    char url[50] = "http://192.168.2.11/app.zip"

    CURL *curl = curl_easy_init();
    if(curl)
    {
    
    
        FILE *fp = fopen(fileName, "w");    // 打开文件,准备写入
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteFunction);
        CURLcode result = curl_easy_perform(curl);

        fclose(fp);                         // 关闭文件
        curl_easy_cleanup(curl);
    }
}

Written by Leung on September 16, 2020

• Reference: libcurl downloads files via http protocol and displays download progress

Guess you like

Origin blog.csdn.net/qq_36347513/article/details/108621872