WinHTTP开发POST表单的问题及解决

转自:http://blog.csdn.net/blog51/article/details/4275632

利用WinHTTP编写访问WEB页面的客户端,如果需要POST表单,比如输入登陆的用户名和密码等等,以后的页面访问都和这个登陆的Session有关。IE浏览器等客户端利用从服务器端获得的Cookie保存相关信息实现会话的一致性,具体到WinHTTP开发,查了一下,网上没有太多相关资料,下面函数利用Get掩饰向一个网站获取Cookie的ID号,保存到CString中,以后的Get等操作,都利用WinHttpAddRequestHeaders将Cookie添加到Header中,然后在进行Request操作即可:

 

CStringW GetCookie()
{
    CStringW strCookie = L"";
    DWORD dwSize = 0;
    LPVOID lpOutBuffer = NULL;
    BOOL  bResults = FALSE;

    HINTERNET  hSession = NULL, 
        hConnect = NULL,
        hRequest = NULL;

    // Use WinHttpOpen to obtain a session handle.
    hSession = WinHttpOpen( SZ_AGENT,  
        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
        WINHTTP_NO_PROXY_NAME, 
        WINHTTP_NO_PROXY_BYPASS, 0 );

    // Specify an HTTP server.
    if( hSession )
        hConnect = WinHttpConnect( hSession, L"wapmail.webdunia.com",
        INTERNET_DEFAULT_HTTP_PORT, 0 );

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

    // Send a request.
    if( hRequest )
        bResults = WinHttpSendRequest( hRequest,
        WINHTTP_NO_ADDITIONAL_HEADERS, 0,
        WINHTTP_NO_REQUEST_DATA, 0, 
        0, 0 );


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

    // First, use WinHttpQueryHeaders to obtain the size of the buffer.
    if (bResults)
    {
        WinHttpQueryHeaders( hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF,
            WINHTTP_HEADER_NAME_BY_INDEX, NULL, 
            &dwSize, WINHTTP_NO_HEADER_INDEX);

        // Allocate memory for the buffer.
        if( GetLastError( ) == ERROR_INSUFFICIENT_BUFFER )
        {
            lpOutBuffer = new WCHAR[dwSize/sizeof(WCHAR)];

            // Now, use WinHttpQueryHeaders to retrieve the header.
            bResults = WinHttpQueryHeaders( hRequest, 
                WINHTTP_QUERY_RAW_HEADERS_CRLF,
                WINHTTP_HEADER_NAME_BY_INDEX, 
                lpOutBuffer, &dwSize, 
                WINHTTP_NO_HEADER_INDEX);
        }
    }

    // Print the header contents.
    char * tmpch = (char *)malloc(sizeof(lpOutBuffer));

    if (bResults)
        sprintf(tmpch,"%S",lpOutBuffer);

    strCookie = tmpch;
    int set_cookie = strCookie.Find(L"Cookie",0);
    int semicolon = strCookie.Find (L";",set_cookie);
    if(set_cookie != -1 && semicolon != -1)
        strCookie = strCookie.Mid (set_cookie,semicolon - set_cookie) + L"/r/n";

    // Free the allocated memory.
    delete [] lpOutBuffer;

    // 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 strCookie;
}

你可能感兴趣的:(C++)