c++ - 如何在 C++ 中使用 winhttp 将 json 数据发布到 api

标签 c++ winapi https

我需要使用 C++ 将 json 数据发布到 api。在 API 中,我还需要包含 app_idapp_key 作为 header 。下面是我正在使用的代码:

std::wstring get_utf16(const std::string &str, int codepage)
{
    if (str.empty()) return std::wstring();
    int sz = MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), 0, 0);
    std::wstring res(sz, 0);
    MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), &res[0], sz);
    return res;
}

LPCWSTR additionalHeaders = L"Content-Type: application/json\r\n" + L"app_id: 7ty44" + L"app_key: e36ff19de5623";
DWORD headersLength = -1;

string HttpsWebRequestPost(string domain, string url, string dat)
{
    //Extra
    LPSTR  data = const_cast<char *>(dat.c_str());;
    DWORD data_len = strlen(data);


    wstring sdomain = get_utf16(domain, CP_UTF8);
    wstring surl = get_utf16(url, CP_UTF8);
    string response;

    DWORD dwSize = 0;
    DWORD dwDownloaded = 0;
    LPSTR pszOutBuffer;
    BOOL  bResults = FALSE;
    HINTERNET  hSession = NULL,
        hConnect = NULL,
        hRequest = NULL;

    // Use WinHttpOpen to obtain a session handle.
    hSession = WinHttpOpen(L"WinHTTP Example/1.0",
        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
        WINHTTP_NO_PROXY_NAME,
        WINHTTP_NO_PROXY_BYPASS, 0);

    // Specify an HTTP server.
    if (hSession)
        hConnect = WinHttpConnect(hSession, sdomain.c_str(),
            INTERNET_DEFAULT_HTTP_PORT, 0);

    // Create an HTTP request handle.
    if (hConnect)
        hRequest = WinHttpOpenRequest(hConnect, L"POST", surl.c_str(),
            NULL, WINHTTP_NO_REFERER,
            WINHTTP_DEFAULT_ACCEPT_TYPES,
            0);

    // Send a request.
    if (hRequest)
        bResults = WinHttpSendRequest(hRequest,
            additionalHeaders,
            headersLength,
            (LPVOID)data,
            data_len,
            data_len,
            0);

    // End the request.
    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);

    // Keep checking for data until there is nothing left.
    if (bResults)
    {
        do
        {
            // Check for available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
                printf("Error %u in WinHttpQueryDataAvailable.\n",
                    GetLastError());

            // Allocate space for the buffer.
            pszOutBuffer = new char[dwSize + 1];
            if (!pszOutBuffer)
            {
                printf("Out of memory\n");
                dwSize = 0;
            }
            else
            {
                // Read the data.
                ZeroMemory(pszOutBuffer, dwSize + 1);

                if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer,
                    dwSize, &dwDownloaded))
                    printf("Error %u in WinHttpReadData.\n", GetLastError());
                else
                    //printf("%s", pszOutBuffer);
                    response = response + string(pszOutBuffer);
                // Free the memory allocated to the buffer.
                delete[] pszOutBuffer;
            }
        } while (dwSize > 0);
    }

    // Report any errors.
    if (!bResults)
        printf("Error %d has occurred.\n", GetLastError());

    // Close any open handles.
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);

    return response;

}

我在 additional headers 中包含了 app_idapp_key 但不确定这是否是正确的方法。另外我如何通过传递我需要发送的 json 数据来调用它。我没有为此找到任何好的工作示例。谢谢

最佳答案

L"Content-Type: application/json\r\n"+ L"app_id: 7ty44"+ L"app_key: e36ff19de5623"

那是行不通的。 C++ 确实有字符串类型,但您在这里使用的是字符串文字。它们具有 wchar_t[LENGTH] 类型,即它们是固定字符数组。并且与字符串类型不同,它们没有operator+

相反,相邻的字符串文字将由编译器连接起来:

LPCWSTR additionalHeaders = 
    L"Content-Type: application/json\r\n"
    L"app_id: 7ty44\r\n"
    L"app_key: e36ff19de5623\r\n"; // << Only this line has a ;

关于c++ - 如何在 C++ 中使用 winhttp 将 json 数据发布到 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56628815/

相关文章:

c++ - 模板和类型转换

c++ - 使用 C++/WinRT 使用设备填充 ListBox,显示它们的名称?

c++ - 小于最小可表示 int 的最小 int 值?

c++ - 在 Windows 8.1 中查找触摸数字化仪的物理尺寸

ssl - 如何在 MAMP Pro 中设置多个支持 https 的子域?

android - 使用 HTTPS 请求发送 JSON 参数

C++ 链接成员函数使用 .chain().method() 与 ->chained(0->method()

c++ - 如何创建具有较低完整性级别 (IL) 的新流程?

iphone - 3G 网络上的 https 连接时间为三秒

c - 从卷 ID 启动 APP