我在使用C ++ JsonCpp库时使用libcurl时遇到了一些问题,经过大量研究后,我想出了这段代码:
int post(const string& call, const string& key, const string& value) {
// (...)
char* char_data=NULL;
struct curl_slist *headers=NULL;
headers = curl_slist_append(headers, "Content-Type: application/json; charset=UTF-8");
Json::Value root;
root[key] = value;
Json::StyledWriter writer;
string data = writer.write(root);
char_data = (char*) malloc((strlen(data.c_str())+1) * sizeof(char));
strcpy(char_data, data.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, char_data);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(char_data));
// (...)
}
只要data
(包含JSON字符串表示的C ++ std::string
)没有任何非ascii字符,这样就可以正常工作。当它发生时,我从后端得到一个错误(用Rails 3编写):
Started POST "/deployments/4c904f607d7c4249cf00002c/log.json" for 67.23.79.89 at Wed Sep 15 00:45:40 -0400 2010
Processing by DeploymentsController#log as JSON
Parameters: {"log"=>"0 upgraded, 0 newly \214\211K########talled, 0 to remove and 46 not upgraded.\n", "id"=>"4c904f607d7c4249cf00002c"}
Completed in 6ms
BSON::InvalidStringEncoding (String not valid UTF-8):
app/models/deployment.rb:161:in `log'
app/models/deployment.rb:160:in `each'
app/models/deployment.rb:160:in `log'
app/controllers/deployments_controller.rb:54:in `log'
获取C ++ sctring(在本例中是数据)的最佳方法是什么,并将其安全地转换为UTF-8,然后转换为与libcurl一起使用的*char
变量?
答案 0 :(得分:1)
我发现了问题。它不是代码的那一部分。我实际上是在做一个导致问题的字符串拆分。