CURL 在发出 http 请求时的奇怪行为(错误 400)
CURL's weird behavior (error 400) when making http request
我有这样的代码可以向 Yandex Translate 发出 http 请求 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);
执行snprintf
后,buf
包含这样的url:
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>
但是如果我在 http 请求后重新分配 char input[1024] = "Hello world.";
(没有 "H"),我会得到正确的响应:
{"code":200,"lang":"en-ru","text":["\"Здравствуй, мир!\"."]}
。
可能是什么问题?
您需要对输入文本进行编码以便在 URL 中使用。试试这个卷曲 function
char *input = curl_easy_escape(curl, "Hello world. H", 0);
我有这样的代码可以向 Yandex Translate 发出 http 请求 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);
执行snprintf
后,buf
包含这样的url:
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>
但是如果我在 http 请求后重新分配 char input[1024] = "Hello world.";
(没有 "H"),我会得到正确的响应:
{"code":200,"lang":"en-ru","text":["\"Здравствуй, мир!\"."]}
。
可能是什么问题?
您需要对输入文本进行编码以便在 URL 中使用。试试这个卷曲 function
char *input = curl_easy_escape(curl, "Hello world. H", 0);