开发者

C++ Windows HTTP

开发者 https://www.devze.com 2022-12-29 13:22 出处:网络
I\'m looking for a basic tutorial for connecting to a domain and downloading the index file . Anyone that can link me a good example or anythin开发者_Python百科g.Check out libCURL it will do this for

I'm looking for a basic tutorial for connecting to a domain and downloading the index file . Anyone that can link me a good example or anythin开发者_Python百科g.


Check out libCURL it will do this for you.


The simplest solution is using URLDownloadToFile.

However, you can use all these APIs together:

  • InternetOpen
  • InternetOpenUrl
  • InternetReadFile
  • InternetCloseHandle

I'm pretty sure there's still another simple API for that, but I don't remember right now.


There is a free HTTP library included with Ultimate TCP/IP.


I use Poco for that. as a side benefir it's also portable (works on Linux and other OSs as well).

void openHttpURL(string host, int port, string path)
{
    try
    {
        HTTPClientSession session(host, port);
    //  session.setTimeout(Timespan(connectionTimeout, 0));
        HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
        session.sendRequest(req);
        HTTPResponse res;
        int code = res.getStatus();
        if (code != res.HTTP_OK)
        {
            stringstream s;
            s << "HTTP Error " << code;
            throw Poco::IOException(s.str());
        }
        std::istream& rs = session.receiveResponse(res);
        int len = res.getContentLength();
        // READ DATA FROM THE STREAM HERE

    }
    catch (Exception& exc)
    {
        stringstream s;
        s << "Error connecting to http://" << host << ':' << port << "/" << path + " : " + exc.displayText();
        throw Poco::IOException(s.str());
    }
}


Generally I'd recommend something cross-platform like cURL, POCO, or Qt. However, here is a Windows example!:

// TODO: error handling

#include <atlbase.h>
#include <msxml6.h>

HRESULT hr;
CComPtr<IXMLHTTPRequest> request;

hr = request.CoCreateInstance(CLSID_XMLHTTP60);
hr = request->open(
    _bstr_t("GET"),
    _bstr_t("https://www.google.com/images/srpr/logo11w.png"),
    _variant_t(VARIANT_FALSE),
    _variant_t(),
    _variant_t());
hr = request->send(_variant_t());

// get status - 200 if succuss
long status;
hr = request->get_status(&status);

// load image data (if url points to an image)
VARIANT responseVariant;
hr = request->get_responseStream(&responseVariant);
IStream* stream = (IStream*)responseVariant.punkVal;
CImage image = new CImage();
image->Load(stream);
stream->Release();
0

精彩评论

暂无评论...
验证码 换一张
取 消