How do you make a HTTP request with C++?

后端 未结 22 2914
有刺的猬
有刺的猬 2020-11-22 06:25

Is there any way to easily make a HTTP request with C++? Specifically, I want to download the contents of a page (an API) and check the contents to see if it contains a 1 o

22条回答
  •  再見小時候
    2020-11-22 07:03

    Here is some (relatively) simple C++11 code that uses libCURL to download a URL's content into a std::vector:

    http_download.hh

    # pragma once
    
    #include 
    #include 
    
    std::vector download(std::string url, long* responseCode = nullptr);
    

    http_download.cc

    #include "http_download.hh"
    
    #include 
    #include 
    #include 
    
    using namespace std;
    
    size_t callback(void* contents, size_t size, size_t nmemb, void* user)
    {
      auto chunk = reinterpret_cast(contents);
      auto buffer = reinterpret_cast*>(user);
    
      size_t priorSize = buffer->size();
      size_t sizeIncrease = size * nmemb;
    
      buffer->resize(priorSize + sizeIncrease);
      std::copy(chunk, chunk + sizeIncrease, buffer->data() + priorSize);
    
      return sizeIncrease;
    }
    
    vector download(string url, long* responseCode)
    {
      vector data;
    
      curl_global_init(CURL_GLOBAL_ALL);
      CURL* handle = curl_easy_init();
      curl_easy_setopt(handle, CURLOPT_URL, url.c_str());
      curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, callback);
      curl_easy_setopt(handle, CURLOPT_WRITEDATA, &data);
      curl_easy_setopt(handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
      CURLcode result = curl_easy_perform(handle);
      if (responseCode != nullptr)
        curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, responseCode);
      curl_easy_cleanup(handle);
      curl_global_cleanup();
    
      if (result != CURLE_OK)
      {
        stringstream err;
        err << "Error downloading from URL \"" << url << "\": " << curl_easy_strerror(result);
        throw runtime_error(err.str());
      }
    
      return move(data);
    }
    

提交回复
热议问题