【问题标题】:WinHTTP Request data in unicode?WinHTTP以unicode请求数据?
【发布时间】:2014-02-01 20:35:48
【问题描述】:

我正在尝试通过 WinHTTP 读取网页:

bool WinHTTPClass::QueryResponseData(std::string &query_data)
{
    // Read response

    DWORD dwSize, dwDownloaded = 0;

    do 
    {
        // Check for available data.  

        if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
        {
            cout << "Error querying data : " << GetLastError() << endl;
            return false;
        }

        // Allocate space for the buffer.

        char* pszOutBuffer = new char[dwSize+1];

        if( !pszOutBuffer )
        {
            cout << "Out of memory" << endl;
            dwSize=0;
        }
        else
        {
            // Read the data.
            ZeroMemory( pszOutBuffer, dwSize+1 );

            if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, 
                                dwSize, &dwDownloaded ) )
            {
                cout << "Error reading data : " << GetLastError() << endl;
                return false;
            }
            else
            {
                query_data += pszOutBuffer;
            }

            // Free the memory allocated to the buffer.
            delete [] pszOutBuffer;
        }
    }
    while( dwSize > 0 );

    return true;
}

这一切都很好。我在这里遇到的困惑是我应该使用 unicode 编码缓冲区而不是处理缓冲区数据:

char* pszOutBuffer = new char[dwSize+1];

比如用wchar_t代替网页常用的UTF8?有什么不同?我哪里糊涂了?

【问题讨论】:

    标签: c++ html unicode winhttp


    【解决方案1】:

    HTTP 是一种二进制传输,它没有文本或 Unicode 的概念。 HTTP 使用 7 位 ASCII 作为 HTTP 标头,但内容是任意二进制数据,其解释取决于描述它的 HTTP 标头,最值得注意的是 Content-Type 标头。因此,您需要先将原始内容数据接收到您的char[] 缓冲区中,然后使用WinHttpQueryHeaders() 查看接收到的Content-Type 标头以查看您接收到的数据类型。如果它说您收到了text/... 类型,那么标题通常还会指定文本的charset。对于text/htmlcharset 可能位于 HTML 本身的 &lt;meta&gt; 标记中,而不是 HTTP 标头中。知道文本的 charset 后,您可以使用 MultiByteToWideChar() 将其转换为 wchar_t[](您必须手动查找字符集的相应代码页)。

    【讨论】:

      猜你喜欢
      • 2011-01-31
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 2012-02-14
      • 2014-05-24
      • 2016-03-05
      • 1970-01-01
      相关资源
      最近更新 更多