只有Fiddler修复了我的WININET GET请求

时间:2016-12-08 16:50:39

标签: c++ json get wininet

我需要向休息服务器发送WININET请求并获得json响应。代码仅在提琴手工作时才有效。我已经尝试了所有我发现的东西但每次进入bytesRead时都是0。没有任何错误,HttpSendRequestandInternetReadFile都返回true,但缓冲区仍为空。

服务器工作正常并以正确的方式回答。当fiddler运行时,我得到了76个字节,这是我需要的。我试图弄清楚使用那个博客Help! Running Fiddler Fixes My App???,没有运气。

HINTERNET session = nullptr;
HINTERNET request = nullptr;
HINTERNET connect = nullptr;
BOOST_SCOPE_EXIT((&session)(&request)(&connect)) {
    if (request != nullptr)
        ::InternetCloseHandle(request);
    if (session != nullptr)
        ::InternetCloseHandle(session);
    if (connect != nullptr)
        ::InternetCloseHandle(connect);
} BOOST_SCOPE_EXIT_END;

try
{
    //std::wstring agent(L"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1");
    std::wstring agent{ L"Mozilla/5.0 (compatible)" };
    session = ::InternetOpen(agent.c_str(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);

    if (!session)
        return;

    InternetSetStatusCallback(
        session,
        (INTERNET_STATUS_CALLBACK)IStatusCallback);

    connect = InternetConnect(
        session
        , serverName.c_str()
        , INTERNET_DEFAULT_HTTP_PORT
        , NULL
        , NULL
        , INTERNET_SERVICE_HTTP
        , 0
        , 1);

    if (!connect)
        return;

    //const wchar_t* parrAcceptTypes[] = { L"text/*", NULL };
    const wchar_t* parrAcceptTypes[] = { L"application/json", L"text/*", NULL };
    request = HttpOpenRequest(
        connect
        , L"GET"
        , virtualFolder.c_str()
        , L"HTTP/1.1"
        , NULL
        , parrAcceptTypes
        , /*INTERNET_FLAG_KEEP_CONNECTION*/INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_PRAGMA_NOCACHE
        , 1);

    std::string data;
    if (request)
    {
        BOOL isRequestComplete = HttpSendRequest(request, NULL, 0, NULL, 0);

        if (isRequestComplete)
        {
            const int dataSize = 1024;

            BYTE buff[dataSize];
            DWORD bytesRead = (DWORD)-1;
            BOOL bKeepReading = true;
            while (bKeepReading && bytesRead != 0)
            {
                bKeepReading = InternetReadFile(request, buff, sizeof(buff) - 1, &bytesRead);
                data.append((char*)buff, bytesRead);
            }
        }
        else
        {
            DWORD dwErr = GetLastError();
            InternetErrorDlg(parent_, request, dwErr, 0, NULL);
            LERR_ << "Request was failed. Error code: " << dwErr;
        }
    }

0 个答案:

没有答案