我试图使用免费的谷歌翻译API,这是从火狐的S3谷歌翻译插件,即。
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 ie中。
$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); }
});但这样做,我得到了谷歌翻译的回应,即。
Error: 400. That’s an error.
Your client has issued a malformed or illegal request. That’s all we know.请帮我解决这个错误并得到翻译的文本。
发布于 2015-07-04 16:17:32
对不起,我试着用同样的代码发邮件,结果成功了..谢谢大家。
发布于 2015-07-03 10:32:55
我在浏览器中检查了您的URL,它显示了400个错误。这意味着非法请求。尝试http://www.sitepoint.com/using-google-translate-api-php/这个网址。
<?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'];
?>发布于 2020-05-17 08:58:50
我在一个Visual 6项目中也有同样的问题,而Thamaraiselvam的评论引导我走向正确的方向。我正确地构建了URL,如果我在浏览器中尝试它,它就能工作,但是在vb6的http组件中它不能工作。解决方案是简单地url_encode发送的数据。(将其放入浏览器是自动完成的)
希望这能帮到别人。
https://stackoverflow.com/questions/31204524
复制相似问题