在WM5.0平台下,用VC8开发,发送POST请求,有两种途径,用SOCKET和WinInet。用WinInet,必须要打上SP1的补丁,否则CInternetSession、CHttpFile等类用不了。具体的请参考:http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q165/2/98.ASP
在VC6下,解析服务器端的数据时,对于UTF-8的转换要进行两次转换才能转成ASCII码,示例代码如下:
CString strURL = "http://www.blog.163.com/login?username=username&pass=pass";
CString strHeader = "Content-Type: application/x-www-form-urlencoded";
CInternetSession session;
CHttpFile* pHttpFile = session.OpenURL(strURL,1, INTERNET_FLAG_TRANSFER_ASCII, strHeader, strHeader.GetLength());
DWORD dwRes;
BOOL res = pHttpFile->QueryInfoStatusCode(dwRes);
CString strSentence, strGetSentence = "";
if (res && dwRes == 200) //返回不一定是200,也可能是201,201,302(重定向)
{
BOOL result = fileGet->SendRequest(strHeaders, (char *)(LPCTSTR)strFormData, strFormData.GetLength());
while(fileGet->ReadString(strSentence)) // 读取提交数据后的返回结果
{
strGetSentence = strGetSentence + strSentence + char(13) + char(10);
strSentence = strSentence + char(13) + char(10);//得到的是一行
char temp[128] = {0};
strcpy(temp,m_strMid.GetBuffer(m_strMid.GetLength()));
int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, temp, strlen(temp), NULL, 0);
//分配空间要给'\0'留个空间,MultiByteToWideChar不会给'\0'空间
wchar_t* wszString = new wchar_t[wcsLen + 1];
//转换
::MultiByteToWideChar(CP_UTF8, NULL, temp, strlen(temp), wszString, wcsLen);
//最后加上'\0'
wszString[wcsLen] = '\0';
int ansiLen = ::WideCharToMultiByte(CP_ACP, NULL, wszString, wcslen(wszString), NULL, 0, NULL, NULL);
//同上,分配空间要给'\0'留个空间
char* szAnsi = new char[ansiLen + 1];
//转换
//unicode版对应的strlen是wcslen
::WideCharToMultiByte(CP_ACP, NULL, wszString, wcslen(wszString), szAnsi, ansiLen, NULL, NULL);
//最后加上'\0'
szAnsi[ansiLen] = '\0';
............szAnsi就是最终的结果
if(wszString)
{
delete []wszString;
wszString = NULL;
}
if (szAnsi)
{
delete []szAnsi;
szAnsi = NULL;
}
}
}
但在VC8.0下,就不一样了。如果用CString来做ReadString的参数,始终得不到ASCII字符,因为VC8下默认的就是宽字符,而UTF-8就是宽字符,所以必须用char*来做ReadString的参数,然后在用函数MultiByteToWideChar转成UNICODE。如果想得到一行数据,就找标记\r\n就可以