curl 获取信息编码问题

Smile_Tiger 2014-05-04 06:25:17
c++ 利用 curl sdk 获取信息,代码如下:


std::string get(const std::string& strURL)
{
memset(szbuffer,0x0,sizeof(szbuffer));
CURL *pCurl = NULL;
pCurl = curl_easy_init();
if(pCurl == NULL)
{
//Print Error Info
}

//这是网上的处理方法,但是运行会crash
//curl_easy_setopt(pCurl,CURLOPT_HTTPHEADER,"content-type: application/x-www-form-urlencoded;charset=UTF-8");

//这是网上的另外一个处理方法,不报错,但是无效
curl_slist *plist = curl_slist_append(NULL, "Content-Type: application/x-www-form-urlencoded; charset=gb2312");

curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, plist);

curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_easy_setopt(pCurl, CURLOPT_ERRORBUFFER, szErrorBuffer);
curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 30000);
curl_easy_setopt(pCurl, CURLOPT_URL, strURL.c_str());
curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, &DownloadData);
curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, szbuffer);
curl_easy_setopt(pCurl, CURLOPT_HEADER, 0);

CURLcode code = curl_easy_perform(pCurl);
if(code != CURLE_OK)
{
//curl_easy_perform failed
}

if (pCurl)
{
curl_easy_cleanup(pCurl);
pCurl = NULL;
}
return szbuffer;
}



测试代码:


std::string path;
path = "http://192.168.1.107:8080/query/user/info.html?param=test";
std::string strRet = get(path.c_str());


浏览器中的结果: "{\"date\":\"\",\"errorMsg\":\"json串为空\",\"map\":null,\"reqTime\":0,\"result\":1}"
c++运行的结果:" {\"date\":\"\",\"errorMsg\":\"json涓蹭负绌篭",\"map\":null,\"reqTime\":0,\"result\":1}"

该怎样正确处理编码?
...全文
139 点赞 收藏 2
写回复
2 条回复
Smile_Tiger 2014年05月05日
已经解决!

//gbk ת utf8
std::string GBKToUTF8(const std::string& strGBK)
{
    std::string strOutUTF8 = "";
    WCHAR * str1;
    int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
    str1 = new WCHAR[n];
    MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
    n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
    char * str2 = new char[n];
    WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
    strOutUTF8 = str2;
    delete[]str1;
    str1 = NULL;
    delete[]str2;
    str2 = NULL;
    return strOutUTF8;
}

//utf-8 ת gbk
std::string UTF8ToGBK(const std::string& strUTF8)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);
    unsigned short * wszGBK = new unsigned short[len + 1];
    memset(wszGBK, 0, len * 2 + 2);
    MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)strUTF8.c_str(), -1, (LPWSTR)wszGBK, len);

    len = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)wszGBK, -1, NULL, 0, NULL, NULL);
    char *szGBK = new char[len + 1];
    memset(szGBK, 0, len + 1);
    WideCharToMultiByte(CP_ACP,0, (LPWSTR)wszGBK, -1, (LPSTR)szGBK, len, NULL, NULL);
    //strUTF8 = szGBK;
    std::string strTemp(szGBK);
    delete[]szGBK;
    delete[]wszGBK;
    return strTemp;
}
回复 点赞
逸萌 2014年05月04日
回复 点赞
发动态
发帖子
C++ 语言
创建于2007-09-28

3.1w+

社区成员

24.8w+

社区内容

C++ 语言相关问题讨论,技术干货分享
社区公告
暂无公告