Google云翻译API v2 – 在处理大文本时遇到错误

huangapple go评论66阅读模式
英文:

Google cloud translate API v2 - getting errors with large text pieces

问题

这段代码似乎是用来调用Google翻译API将网站页面内容从英语翻译成丹麦语的。但是,你遇到了HTTP错误403和400。以下是代码中涉及到的翻译部分:

$sendParamsObj = [
    "key" => "insert api key",
    "source" => 'en-us',
    "target" => 'da-dk',
    "q" => 'smaller amount of <strong>content</strong> to translate'
];

你提到使用GET请求可以正常工作,但对于大文本/HTML片段,可能会出现HTTP请求失败的问题。而使用POST和JSON时,你遇到了403错误。

从提供的信息来看,403错误通常与API密钥或权限相关。请确保你的API密钥有效,并且具有足够的权限来执行翻译操作。你也可以检查API密钥是否正确设置在 $sendParamsObj 数组中的 "key" 键中。

另外,403错误也可能与服务器的防火墙或访问控制策略有关。如果你确定API密钥无误,可以尝试联系API提供商,以获取更多关于403错误的帮助和解决方案。

对于POST请求,确保你的cURL请求设置正确,并且请求主体正确编码为JSON。你已经设置了正确的请求头 "Content-Type: application/json"

总之,首先确认API密钥和权限设置是否正确,然后检查代码中的cURL请求设置是否准确,以确保你的请求被正确处理。如果问题仍然存在,可能需要进一步调试或与API提供商联系以获取支持。

英文:

I have this code which I am trying to use to translate my website page content:

  $url = &quot;https://translation.googleapis.com/language/translate/v2&quot;;
  $sendParamsObj = [
      &quot;key&quot; =&gt; &quot;insert api key&quot; 
      ,
      &quot;source&quot; =&gt; &#39;en-us&#39;
      ,
      &quot;target&quot; =&gt; &#39;da-dk&#39; 
      ,
      &quot;q&quot; =&gt; &#39;smaller amount of &lt;strong&gt;content&lt;/strong&gt; to translate&#39;
  ];                    
  $myBodyReturn = null;          
  if (true) {
    /*
      This errors: Failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
    */  
    $sendParamsStrJson = json_encode($sendParamsObj);
    $sendOptions = array(
      &#39;http&#39; =&gt; array(
        &#39;method&#39;  =&gt; &#39;POST&#39;,
        &#39;content&#39; =&gt; $sendParamsStrJson,                
        &#39;header&#39;=&gt;  &#39;Content-Type: application/json&#39;
      )
    );                          
    $myContext = stream_context_create($sendOptions);            
    $myBodyReturn = file_get_contents($url, false, $myContext); 
  }  
  else {            
    /*
     For large text/html pieces this probably exceeds GET length (?) and erros: 
       Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request 
    */ 
    $sendParamsQuery = http_build_query($sendParamsObj);
    $myBodyReturn = file_get_contents($url . &quot;?&quot; . $sendParamsQuery);                        
  }
 var_dump($myBodyReturn);          

As can be seen, if I use the top "if (true)" solution using POST and JSON I get error 403...

But if I use "else" solution building GET query this fails with error 400 for large text/HTML pieces

...

Trying something different also gives 403:

$url = &quot;https://translation.googleapis.com/language/translate/v2&quot;;
$sendParamsArr = array(
    &quot;key&quot; =&gt; &quot;my key&quot; 
    ,
    &quot;source&quot; =&gt; &#39;en-us&#39;
    ,
    &quot;target&quot; =&gt; &#39;da-dk&#39; 
    ,
    &quot;q&quot; =&gt; &#39;smaller amount of &lt;strong&gt;content&lt;/strong&gt; to translate&#39;
);                                                  
$data_json = json_encode($sendParamsArr);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    &#39;Content-Type: application/json&#39;,
    &#39;Content-Length: &#39; . strlen($data_json)
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$myBodyReturn = curl_exec($ch);
$res_responsecode_page = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);                  
curl_close($ch);

...

So it appears to work when using GET (but that only supports short text pieces) but not when using POST/JSON

Since it works using GET it is probably not API key issue. Any ideas?

答案1

得分: 2

I recommend using the Google Translate API with translate.googleapis.com to make it easier to translate without an API KEY.

<?php
function translate($txt, $sourceLang, $targetLang)
{
  $url = "https://translate.googleapis.com/translate_a/single?client=gtx&amp;sl=" . $sourceLang . "&amp;tl=" . $targetLang . "&amp;dt=t&amp;q=" . urlencode($txt);
  $response = file_get_contents($url);
  $data = json_decode($response);
  $finaltext = '';
  if ($data[0]) $finaltext = '';
  for ($i = 0; $i < count($data[0]); $i++) {
    $finaltext .= $data[0][$i][0];
  };
  return $finaltext;
}

echo translate('smaller amount of <strong>content</strong> to translate', 'en', 'da');

output: mindre mængde indhold at oversætte

英文:

I recommend using google translate API with translate.googleapis.com to make it easier to translate without API KEY.

&lt;?php
function translate($txt, $sourceLang, $targetLang)
{
  $url = &quot;https://translate.googleapis.com/translate_a/single?client=gtx&amp;sl=&quot; . $sourceLang . &quot;&amp;tl=&quot; . $targetLang . &quot;&amp;dt=t&amp;q=&quot; . urlencode($txt);
  $response = file_get_contents($url);
  $data = json_decode($response);
  $finaltext = &#39;&#39;;
  if ($data[0]) $finaltext = &#39;&#39;;
  for ($i = 0; $i &lt; count($data[0]); $i++) {
    $finaltext .= $data[0][$i][0];
  };
  return $finaltext;
}

echo translate(&#39;smaller amount of &lt;strong&gt;content&lt;/strong&gt; to translate&#39;, &#39;en&#39;, &#39;da&#39;);

output: mindre mængde indhold at oversætte

答案2

得分: 2

POST应该是支持的,但我没有看到https://cloud.google.com/translate/docs/reference/rest/v2/translate中提到JSON,它说"查询参数"。

尝试进行application/x-www-form-urlencoded请求。

返回的HTML标签会发生变化,例如"<"变成了"u003c"。

实际上是\u003C,我想是这样的吧?这是使用PHP的json_encode并设置JSON_HEX_TAG标志时的结果。不确定为什么他们会在GET和POST中使用不同的编码选项,但在解码这个JSON后,你应该以任何方式都会得到一个&lt;

英文:

POST should be supported, but I don't see https://cloud.google.com/translate/docs/reference/rest/v2/translate mentioning JSON, it says "query parameters".

Try making an application/x-www-form-urlencoded request.

> return HTML tags changed, e.g. "<" becomes "u003c"

Actually \u003C, I suppose? That is what you would get with PHP's json_encode with the JSON_HEX_TAG flag set. Not sure why they would use different encoding options for GET vs POST, but after you decoded this JSON, you should get a &lt; either way.

答案3

得分: 0

It is indeed a get request and not a post request(更好,因为它将缓存查询)。所以如果你是从云控制台获取的有效密钥,那么这并不是一个API密钥问题。

英文:

It is indeed a get request and not a post request (better since it will cache queries). So it is not an API key issue if it is a valid key that you got it from the cloud console.

huangapple
  • 本文由 发表于 2023年5月11日 17:47:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226285.html
  • google-cloud-platform
  • google-cloud-translate
  • google-translate
  • google-translation-api
  • php
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定