我正在製作一個C++代理,它將使用HttpSendRequest()將信息(例如系統主機名)發回中央服務器。我希望它回發的一條信息是操作系統。我創建了以下函數來獲取系統主機名。HttpSendRequest - 不支持Unicode的POST數據
wstring getOS()
{
HKEY key;
RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_QUERY_VALUE, &key); // Obtains Registry handle
DWORD type;
wchar_t buffer[MAX_PATH]; // MAX_PATH = 260 - The system hostname should never exceed this value
DWORD size = sizeof(buffer);
RegQueryValueEx(key, L"ProductName", NULL, &type, (LPBYTE)&buffer, &size); // Queries Registry key - stores value in "buffer"
wstring os(buffer); // Converts from C-style character array to wstring
return os; // Returns wstring to caller
}
該函數將使用註冊表獲取操作系統並將其存儲爲wstring。然後,我想要將返回的「os」wstring傳遞給下面的post()函數,但我注意到您必須使用字符串而不是wstring作爲HTTP POST數據。下面是我的職位代碼()函數:
void post()
{
HINTERNET hInternetOpen = InternetOpen(userAgent.c_str(), INTERNET_OPEN_TYPE_PROXY, L"http://127.0.0.1:9999", NULL, 0);
HINTERNET hInternetConnect = InternetConnect(hInternetOpen, host.c_str(), INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
HINTERNET hHttpOpenRequest = HttpOpenRequest(hInternetConnect, L"POST", file.c_str(), NULL, NULL, NULL, 0, 0);
wstring headers = L"Content-Type: application/x-www-form-urlencoded"; // Content-Type is necessary to POST
string postData = "os="; // Why does this have to be a string and not a wstring?
HttpSendRequest(hHttpOpenRequest, headers.c_str(), headers.length(), (LPVOID)postData.c_str(), postData.size());
InternetCloseHandle(hInternetOpen);
InternetCloseHandle(hInternetConnect);
InternetCloseHandle(hHttpOpenRequest);
}
如果我試圖讓「POSTDATA」一個wstring的,我得到的東西看起來像下面的圖片:
可有人闡明瞭將wstring作爲POST數據的最簡單方法?
你爲什麼說你 '必須使用字符串,而不是wstring的'? – pm100
如果我嘗試使用wstring而不是字符串,它會擾亂POST數據(請參閱附加的屏幕截圖)。 – t3ntman
你想在電匯上發送什麼? UTF8?請參閱這裏http://stackoverflow.com/questions/148403/utf8-to-from-wide-char-conversion-in-stl – pm100