Winsocket recv 乱码问题
小弟闲来无事 将以前用C#写的一段httpreqest 代码改成C++的,历经千辛万苦终于可以执行了。可以在访问某些中文网站时, 获取的字符流里面有乱码。
先贴代码:
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string> #include <winsock2.h> #pragma comment(lib, "WS2_32") #include <iostream>void SendString(SOCKET sock, LPCSTR str){ send(sock,str,strlen(str),0);}bool HttpClient() { WSADATA ws; SOCKET s; struct sockaddr_in addr; struct hostent *pHostent; int iResult; long lResult; char strSubAddr[100], strBuffer[100]; lResult = WSAStartup(0x0101,&ws); s = socket(AF_INET,SOCK_STREAM,0); char ina[]="www.tianya.cn"; //下面将网址转换成IP地址: pHostent = gethostbyname(ina); addr.sin_family = AF_INET; addr.sin_port = htons(80); addr.sin_addr.s_addr = *(unsigned long *)pHostent->h_addr_list[0]; iResult=connect(s,(struct sockaddr *) &addr, sizeof(addr)); if(SOCKET_ERROR == iResult) { // 连接失败 WSACleanup(); return FALSE; } else { //这里是要发送的http头部 SendString(s, "GET / HTTP/1.1\r\n"); SendString(s, "Host: www.tianya.cn/publicforum/articleslist/0/feeling.shtml\r\n"); SendString(s, "Accept: */*\r\n"); SendString(s, "Content-Type: application/x-www-form-urlencoded"); //SendString(s, "User-Agent: Mozilla/4.0"); //SendString(s, "(compatible; MSIE 7.00; Windows 98)\r\n"); //SendString(s, "Connection:Keep-Alive\r\n"); SendString(s, "\r\n"); SendString(s, "\r\n");//最后要加空行 iResult = 1; // 获取返回字符流 while( iResult >0 ) { strset(strBuffer,' '); //这里的strBuffer老是有乱码 我试过百度也有乱码 iResult = recv(s,strBuffer,100,0); std::cout<<strBuffer; } } delete strBuffer; closesocket(s); WSACleanup(); return TRUE; } void main(){ HttpClient(); std::cout<<"";}iResult = recv(s,strBuffer,100000,0); MultiByteToWideChar( CP_UTF8, 0, strBuffer, (int) strlen(strBuffer)+1, wscBuffer, sizeof(wscBuffer)/sizeof(wchar_t) ); WideCharToMultiByte( CP_ACP, 0, wscBuffer, -1,strBuffer, 100000, NULL, NULL ); std::cout<<strBuffer;
[解决办法]
没有直接utf-8 =》ansi
用unicode做中转 utf-8 => unicode =>ansi
[解决办法]
又是UTF8...伤不起啊...