WinInet在char / string c ++上存储读取文件

时间:2018-03-11 21:16:36

标签: c++ wininet

#include <WinInet.h>
#pragma comment(lib, "wininet")

void download(std::string domain, std::string url)
{
    HINTERNET hIntSession = InternetOpenA("MyApp", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    HINTERNET hHttpSession = InternetConnectA(hIntSession, domain.c_str(), 80, 0, 0, INTERNET_SERVICE_HTTP, 0, NULL);
    HINTERNET hHttpRequest = HttpOpenRequestA(hHttpSession, "GET", url.c_str(), 0, 0, 0, INTERNET_FLAG_RELOAD, 0);
    TCHAR* szHeaders = "";
    CHAR szReq[1024] = "";
    if (!HttpSendRequest(hHttpRequest, szHeaders, wcslen(L""), szReq, strlen(szReq))){
        MessageBoxA(NULL, "No se puede conectar al Servidor de Actualizaciones.", "Error Kundun", MB_OK | MB_ICONERROR);
    }
    TCHAR szBuffer[1025];
    DWORD dwRead = 0;
    while (InternetReadFile(hHttpRequest, szBuffer, 1024, &dwRead) && dwRead)
    {
        // What to do here?
    }
    InternetCloseHandle(hHttpRequest);
    InternetCloseHandle(hHttpSession);
    InternetCloseHandle(hIntSession);
}

download("www.something.com", "File.txt");

所以我有这段代码从托管上的文本文件中读取内容。我设法通过谷歌搜索得到它,它似乎工作得很好(如果我把一个不正确的域,它将显示错误的消息框)。事情是..我不知道如何将我刚读到的信息放入字符串或char []。

1 个答案:

答案 0 :(得分:0)

szBuffer更改为char[],然后在循环中使用std::string::append()

#include <WinInet.h>
#pragma comment(lib, "wininet")

void download(const std::string & domain, const std::string &url)
{
    HINTERNET hIntSession = InternetOpenA("MyApp", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    HINTERNET hHttpSession = InternetConnectA(hIntSession, domain.c_str(), 80, 0, 0, INTERNET_SERVICE_HTTP, 0, NULL);
    HINTERNET hHttpRequest = HttpOpenRequestA(hHttpSession, "GET", url.c_str(), 0, 0, 0, INTERNET_FLAG_RELOAD, 0);
    if (!HttpSendRequestA(hHttpRequest, NULL, 0, NULL, 0))
    {
        MessageBoxA(NULL, "No se puede conectar al Servidor de Actualizaciones.", "Error Kundun", MB_OK | MB_ICONERROR);
    }
    char szBuffer[1024];
    DWORD dwRead = 0;
    std::string data;
    while (InternetReadFile(hHttpRequest, szBuffer, 1024, &dwRead) && dwRead)
    {
        data.append(szBuffer, dwRead);
    }
    InternetCloseHandle(hHttpRequest);
    InternetCloseHandle(hHttpSession);
    InternetCloseHandle(hIntSession);
    // use data as needed...
}