google 中的 400 个错误请求使用 curl 免费翻译 api

400 bad request in google translate free api using curl

我正在尝试使用从 Firefox 的 S3 Google 翻译插件中提取的免费 Google 翻译 API,即

https://translate.google.com/translate_a/single?client=t&sl=auto&
tl=en&hl=en&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t
&dt=at&ie=UTF-8&oe=UTF-8&otf=2&srcrom=1&ssel=0&tsel=0&q=Hello

在 PHP cURL 即

$isPOST=isset($_POST) && !empty($_POST);
$q=$isPOST ? $_POST['q'] : $_GET['q'];

$url='https://translate.google.com/translate_a/single';
$data='client=t&sl=auto&tl=en&hl=en&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&srcrom=1&ssel=0&tsel=0&q='.$q;
$ch=curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_URL, !$isPOST ? $url.'?'.$data : $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if($isPOST){
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$return=curl_exec($ch);
curl_close($ch);

我正在使用 ajax..

调用此页面
$.ajax({
    type: text.length>750 ? 'post' : 'get',
    url: 'translate.php',
    data: 'q='+text,
    success: function(d){ alert(d); }
});

但是做这一切,我从 Google 翻译得到这个回复,即

Error: 400. That’s an error.
Your client has issued a malformed or illegal request. That’s all we know.

请帮我解决这个错误并获取翻译后的文本..

我在你的浏览器中检查了你的 URL 它显示 400 错误。这意味着非法请求。 试试 http://www.sitepoint.com/using-google-translate-api-php/ 这个 URL.

<?php
    $apiKey = '<paste your API key here>';
    $text = 'Hello world!';
    $url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=en&target=fr';

    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($handle);                 
    $responseDecoded = json_decode($response, true);
    curl_close($handle);

    echo 'Source: ' . $text . '<br>';
    echo 'Translation: ' . $responseDecoded['data']['translations'][0]['translatedText'];
?>

抱歉,我尝试 POST 使用相同的代码并且成功了.. 谢谢大家

我在 Visual Basic 6 项目中遇到了同样的问题,Thamaraiselvam 的评论引导我找到了正确的方向。 我正在正确构建 URL,如果我在浏览器中尝试它,它可以工作,但在 vb6 的 http 组件中它不工作。解决方案是简单地 url_encode 发送数据。 (放在浏览器里是自动完成的)

希望这对其他人有帮助。