我有这样的代码向Yandex Translate API提出http请求:
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);
执行snprintf
后,buf
包含此类网址:
https://translate.yandex.net/api/v1.5/tr.json/translate?key=secret.key.here&lang=ru&text="Hello world. H"
在回复后,response.data
包含:
<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>
但是如果我重新分配char input[1024] = "Hello world.";
(没有“H”),在http请求之后,我得到了正确的回复:
{"code":200,"lang":"en-ru","text":["\"Здравствуй, мир!\"."]}
。
可能是什么问题?
答案 0 :(得分:3)
您需要对输入文本进行编码以便在URL中使用。试试这个卷曲function
char *input = curl_easy_escape(curl, "Hello world. H", 0);