[400 Google中的错误请求使用curl转换了免费api

问题描述 投票:4回答:3

我正在尝试使用免费的Google Translate API,该API是从Firefox的S3 Google Translator插件中提取的,例如。>

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 Translate得到了这个答复,即。

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

[请帮助我解决此错误并获取翻译后的文本。。

我正在尝试使用免费的Google Translate API,该API是从Firefox的S3 Google Translator插件中提取的。 https://translate.google.com/translate_a/single?client=t&sl=auto& tl = en&hl = ...

javascript php ajax curl http-status-code-400
3个回答
1
投票

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


1
投票

[抱歉,我尝试使用相同的代码进行POST,并且可以正常工作。谢谢所有人。


0
投票

我在Visual Basic 6项目中遇到了同样的问题,Thamaraiselvam的评论将我引向了正确的方向。我正在正确地构建URL,并且如果在浏览器中尝试它可以运行,但是在vb6的http组件中却无法运行。解决方案是简单地对发送的数据进行url_encode。 (将其放在浏览器中是自动执行的)

© www.soinside.com 2019 - 2024. All rights reserved.