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

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

    Note that this does not require libcurl, Windows.h, or WinSock! No compilation of libraries, no project configuration, etc. I have this code working in Visual Studio 2017 c++ on Windows 10:

    #pragma comment(lib, "urlmon.lib")
    
    #include 
    #include 
    
    using namespace std;
    
    ...
    
    IStream* stream;
    //Also works with https URL's - unsure about the extent of SSL support though.
    HRESULT result = URLOpenBlockingStream(0, "http://google.com", &stream, 0, 0);
    if (result != 0)
    {
        return 1;
    }
    char buffer[100];
    unsigned long bytesRead;
    stringstream ss;
    stream->Read(buffer, 100, &bytesRead);
    while (bytesRead > 0U)
    {
        ss.write(buffer, (long long)bytesRead);
        stream->Read(buffer, 100, &bytesRead);
    }
    stream.Release();
    string resultString = ss.str();
    

    I just figured out how to do this, as I wanted a simple API access script, libraries like libcurl were causing me all kinds of problems (even when I followed the directions...), and WinSock is just too low-level and complicated.

    I'm not quite sure about all of the IStream reading code (particularly the while condition - feel free to correct/improve), but hey, it works, hassle free! (It makes sense to me that, since I used a blocking (synchronous) call, this is fine, that bytesRead would always be > 0U until the stream (ISequentialStream?) is finished being read, but who knows.)

    See also: URL Monikers and Asynchronous Pluggable Protocol Reference

提交回复
热议问题