C++ wininet,连接weblogin,如何设置cookies?

Posted

技术标签:

【中文标题】C++ wininet,连接weblogin,如何设置cookies?【英文标题】:C++ wininet, connect to weblogin, how to set cookies? 【发布时间】:2011-02-11 18:47:14 【问题描述】:

大家好,我想用 wininet 登录我的作品网页,这是我当前的代码:

int main()

    HINTERNET hInet = InternetOpenA("UserAgent/1.0", INTERNET_OPEN_TYPE_PRECONFIG,0, 0, 0 );
    if(!hInet)
    
        printf("hInet Failed!\n");
        return -1;
    

    HINTERNET hConnection = InternetConnectA( hInet,"app.tamigo.com",INTERNET_DEFAULT_HTTPS_PORT,"","", INTERNET_SERVICE_HTTP,0,0);
    if (!hConnection)
    
        InternetCloseHandle(hInet);
        printf("InternetConnectA failed!\n");
        return -1;
    

    HINTERNET hRequest = HttpOpenRequestA( hConnection, "Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",NULL,"https://app.tamigo.com/Home/Pages/Login.aspx", NULL, INTERNET_FLAG_KEEP_CONNECTION, 0 );
    if (!hRequest)
    
        printf("BuildRequestHeader failed %d!\n",GetLastError());
        InternetCloseHandle(hConnection);
        InternetCloseHandle(hInet);
        return -1;
    

    HttpSendRequestA(hRequest, NULL, 0, NULL, 0);

    DWORD dwInfoLevel = HTTP_QUERY_RAW_HEADERS_CRLF;
    DWORD dwInfoBufferLength = 10;
    BYTE *pInfoBuffer = (BYTE *)malloc(dwInfoBufferLength+1);
    while (!HttpQueryInfo(hRequest, dwInfoLevel, pInfoBuffer, &dwInfoBufferLength, NULL))
    
        DWORD dwError = GetLastError();
        if (dwError == ERROR_INSUFFICIENT_BUFFER)
        
            free(pInfoBuffer);
            pInfoBuffer = (BYTE *)malloc(dwInfoBufferLength+1);
        
        else
        
            fprintf(stderr, "HttpQueryInfo failed, error = %d (0x%x)\n",
            GetLastError(), GetLastError());
            break;
        
    
    pInfoBuffer[dwInfoBufferLength] = '\0';
    printf("%s", pInfoBuffer);
    free(pInfoBuffer);

    cin.get();
    return 1;

如果此代码正确,我必须使用我的用户名登录并通过,我使用“Firefox 插件篡改数据”获得了一个 cookie。如何用 wininet 设置这个 cookie?

非常感谢您的阅读和您的时间

【问题讨论】:

顺便说一句,如果您使用的是 c++,则没有理由使用 malloc 和 free。使用 new 和 delete 运算符。此外,在这种情况下,您根本不需要分配堆。在堆栈上创建缓冲区并将地址传递给 HTTPQueryInfo。 【参考方案1】:

如果 cookie 在之前的 WinInet 请求中已经存在,则 WinInet 将自动发送它。但是,如果 cookie 不存在于 WinInet 的 cookie 缓存中(例如,如果您从其他来源获取 cookie),那么您将必须使用 HttpAddRequestHeaders() 提供您自己的 Cookie: 请求标头,然后再调用 HttpSendRequest()

【讨论】:

以上是关于C++ wininet,连接weblogin,如何设置cookies?的主要内容,如果未能解决你的问题,请参考以下文章

C++ WinINet InternetReadFile函数刷新

如何在 C++ 中使用 wininet 创建 POST 请求

C++ 使用 WinINet 上传到 FTP 服务器

在 C++ 中使用 wininet

如何在 WinInet C++ 中获取 FTP 下载的进度

C++ Wininet 自定义 http 标头