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

后端 未结 22 2492
有刺的猬
有刺的猬 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:06

    If you are looking for a HTTP client library in C++ that is supported in multiple platforms (Linux, Windows and Mac) for consuming Restful web services. You can have below options.

    1. QT Network Library - Allows the application to send network requests and receive replies
    2. C++ REST SDK - An emerging third-party HTTP library with PPL support
    3. Libcurl - It is probably one of the most used http lib in the native world.
    0 讨论(0)
  • 2020-11-22 07:07

    Here is my minimal wrapper around cURL to be able just to fetch a webpage as a string. This is useful, for example, for unit testing. It is basically a RAII wrapper around the C code.

    Install "libcurl" on your machine yum install libcurl libcurl-devel or equivalent.

    Usage example:

    CURLplusplus client;
    string x = client.Get("http://google.com");
    string y = client.Get("http://yahoo.com");
    

    Class implementation:

    #include <curl/curl.h>
    
    
    class CURLplusplus
    {
    private:
        CURL* curl;
        stringstream ss;
        long http_code;
    public:
        CURLplusplus()
                : curl(curl_easy_init())
        , http_code(0)
        {
    
        }
        ~CURLplusplus()
        {
            if (curl) curl_easy_cleanup(curl);
        }
        std::string Get(const std::string& url)
        {
            CURLcode res;
            curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
            curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
    
            ss.str("");
            http_code = 0;
            res = curl_easy_perform(curl);
            if (res != CURLE_OK)
            {
                throw std::runtime_error(curl_easy_strerror(res));
            }
            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
            return ss.str();
        }
        long GetHttpCode()
        {
            return http_code;
        }
    private:
        static size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp)
        {
            return static_cast<CURLplusplus*>(userp)->Write(buffer,size,nmemb);
        }
        size_t Write(void *buffer, size_t size, size_t nmemb)
        {
            ss.write((const char*)buffer,size*nmemb);
            return size*nmemb;
        }
    };
    
    0 讨论(0)
  • 2020-11-22 07:08

    Although a little bit late. You may prefer https://github.com/Taymindis/backcurl .

    It allows you to do http call on mobile c++ development. Suitable for Mobile game developement

    bcl::init(); // init when using
    
    bcl::execute<std::string>([&](bcl::Request *req) {
        bcl::setOpts(req, CURLOPT_URL , "http://www.google.com",
                 CURLOPT_FOLLOWLOCATION, 1L,
                 CURLOPT_WRITEFUNCTION, &bcl::writeContentCallback,
                 CURLOPT_WRITEDATA, req->dataPtr,
                 CURLOPT_USERAGENT, "libcurl-agent/1.0",
                 CURLOPT_RANGE, "0-200000"
                );
    }, [&](bcl::Response * resp) {
        std::string ret =  std::string(resp->getBody<std::string>()->c_str());
        printf("Sync === %s\n", ret.c_str());
    });
    
    
    bcl::cleanUp(); // clean up when no more using
    
    0 讨论(0)
  • 2020-11-22 07:09

    Update 2020: I have a new answer that replaces this, now 8-years-old, one: https://stackoverflow.com/a/61177330/278976

    On Linux, I tried cpp-netlib, libcurl, curlpp, urdl, boost::asio and considered Qt (but turned it down based on the license). All of these were either incomplete for this use, had sloppy interfaces, had poor documentation, were unmaintained or didn't support https.

    Then, at the suggestion of https://stackoverflow.com/a/1012577/278976, I tried POCO. Wow, I wish I had seen this years ago. Here's an example of making an HTTP GET request with POCO:

    https://stackoverflow.com/a/26026828/2817595

    POCO is free, open source (boost license). And no, I don't have any affiliation with the company; I just really like their interfaces. Great job guys (and gals).

    https://pocoproject.org/download.html

    Hope this helps someone... it took me three days to try all of these libraries out.

    0 讨论(0)
  • 2020-11-22 07:09

    C++ does not provide any way to do it directly. It would entirely depend on what platforms and libraries that you have.

    At worst case, you can use the boost::asio library to establish a TCP connection, send the HTTP headers (RFC 2616), and parse the responses directly. Looking at your application needs, this is simple enough to do.

    0 讨论(0)
  • 2020-11-22 07:09

    C and C++ don't have a standard library for HTTP or even for socket connections. Over the years some portable libraries have been developed. The most widely used, as others have said, is libcurl.

    Here is a list of alternatives to libcurl (coming from the libcurl's web site).

    Also, for Linux, this is a simple HTTP client. You could implement your own simple HTTP GET client, but this won't work if there are authentication or redirects involved or if you need to work behind a proxy. For these cases you need a full-blown library like libcurl.

    For source code with libcurl, this is the closest to what you want (Libcurl has many examples). Look at the main function. The html content will be copied to the buffer, after a successfully connection. Just replace parseHtml with your own function.

    0 讨论(0)
提交回复
热议问题