Win32中用于本机C/C++的高级HTTP客户端库

Gui*_*ici 11 c++ winapi client http

在Win32中没有用于本机C/C++的"高级"HTTP库,或者我只是在错误的地方寻找?

"高级"是指一种API,它允许我使用与.NET框架"大致相同"的抽象级别在C++中执行HTTP Web请求/响应(但请注意,使用C++/CLI不是我的选择).

如何在不使用.NET的情况下在Win32中的C/C++中执行此类操作(具有大约相同数量的代码)?作为参考,我提供了一个代码示例来说明我是如何在C#中完成的.

byte[] fileBytes = null;
bool successfulDownload = false;
using (WebClient client = new WebClient())
{
    WebProxy proxy = WebProxy.GetDefaultProxy();
    client.Proxy = proxy;
tryAgain:
    try
    {
        fileBytes = client.DownloadData(fileUrl);
        successfulDownload = true;
    }
    catch (WebException wEx)
    {
        if (wEx.Response != null && wEx.Response is HttpWebResponse)
        {
            string username = null, password = null;
            bool userCanceled = false;
            HttpStatusCode statusCode = ((HttpWebResponse)wEx.Response).StatusCode;
            switch (statusCode)
            {
                case HttpStatusCode.ProxyAuthenticationRequired:
                    // This is just a convenience function defined elsewhere
                    GetAuthenticationCredentials(fileUrl, true,
                        out username, out password, out userCanceled);
                    if (!userCanceled)
                    {
                        client.Proxy.Credentials = new NetworkCredential(username, password);
                        goto tryAgain;
                    }
                    break;
                case HttpStatusCode.Unauthorized:
                    // This is just a convenience function defined elsewhere
                    GetAuthenticationCredentials(fileUrl, false,
                        out username, out password, out userCanceled);
                    if (!userCanceled)
                    {
                        client.Credentials = new NetworkCredential(username, password);
                        goto tryAgain;
                    }
                    break;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Goz*_*Goz 8

Win32提供了这些Internet*功能.

http://msdn.microsoft.com/en-us/library/aa385473(VS.85).aspx

你需要做一个(IIRC,我还没有触及这些API超过10年)InternetOpenURL和InternetReadFile.


unw*_*ind 7

我认为libcurl符合这些要求.然后还有一些.

此示例显示如何获取HTTP页面,仅将其存储在内存中.这是比你的例子更多的代码,但它在C中.


Mat*_*tyT 7

除了libcurl/curlpp(灵活而强大,但我觉得非常......笨重)之外,还有两个我正在关注的C++库.两者都是全新的,基于Boost :: ASIO.但是没有支持代理(我能说的最好).

cpp-netlib(博客)可能更成熟(我知道它有一些真实的测试),但目前缺乏超时(我正在努力!).例:

network::http::request  request("http://google.com");
network::http::client   client;
network::http::response response;

response = client.get(request);
if (response.status() == 200)
{
    std::cout << body(response));
}
Run Code Online (Sandbox Code Playgroud)

Urdl(文档)由ASIO创建者编写并具有超时(但仅在上个月宣布).它使用不同的模型,选择使用流:

urdl::istream is("http://google.com");
std::string line;
while (std::getline(is, line))
{
    std::cout << line << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我同意C++对HTTP没有很好的支持,但这两个库都显示出很多希望.