2010-09-15 7 views
1

J'ai eu quelques problèmes pour faire le travail libcurl avec la bibliothèque C++ JsonCpp et, après beaucoup de recherches, je suis venu avec ce code:C++, JsonCpp, libcurl et UTF-8 malheurs

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)); 

    // (...) 
} 

Cela fonctionne très bien, Tant que le data (C++ std::string qui contient la représentation de chaîne JSON) n'a aucun caractère non-ascii. Quand il le fait, je reçois une erreur du backend (écrit dans 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' 

Quelle est la meilleure façon de prendre un C++ sctring (dans ce cas, les données), et convertir en toute sécurité UTF-8, puis à une variable *char qui jouerait bien avec libcurl?

Répondre

1

J'ai trouvé le problème. Ce n'était pas sur cette partie du code. Je faisais en fait une fente de chaîne qui causait le problème.