Reputation: 1104
I have such code that makes http request to Yandex Translate API:
const char url[] = "https://translate.yandex.net/api/v1.5/tr.json/translate";
const char key[] = "secret.key.here";
char buf[4096] = { 0 };
char input[1024] = "Hello world. H";
snprintf(buf, sizeof(buf), "%s?key=%s&lang=ru&text=\"%s\"",
url, key, input);
struct string response;
init_string(&response);
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, buf);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
curl_easy_cleanup(curl);
}
printf("%s\n", response.data);
After snprintf
execution, buf
contains such url:
https://translate.yandex.net/api/v1.5/tr.json/translate?key=secret.key.here&lang=ru&text="Hello world. H"
and after response, response.data
contains:
<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.6.2</center>
</body>
</html>
but if I reassign char input[1024] = "Hello world.";
(without "H"), after http request, I get the proper response:
{"code":200,"lang":"en-ru","text":["\"Здравствуй, мир!\"."]}
.
What could be the problem?
Upvotes: 1
Views: 988
Reputation: 100
You need to encode your input text for usage in URL. Try this curl function
char *input = curl_easy_escape(curl, "Hello world. H", 0);
Upvotes: 3