You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Cloud Translate API v2处理大文本时遇请求错误

Google翻译API请求问题排查与解决思路

我尝试用PHP调用Google翻译API处理网页内容翻译,遇到了两种请求方式的问题,具体如下:

1. 初始实现的两种请求方式及问题

POST+JSON方式(触发403 Forbidden错误)

代码实现:

$url = "https://translation.googleapis.com/language/translate/v2";
$sendParamsObj = [
    "key" => "insert api key" 
    ,
    "source" => 'en-us'
    ,
    "target" => 'da-dk' 
    ,
    "q" => 'smaller amount of <strong>content</strong> to translate'
];                    
$myBodyReturn = null;          
if (true) {
    /*
      This errors: Failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
    */  
    $sendParamsStrJson = json_encode($sendParamsObj);
    $sendOptions = array(
      'http' => array(
        'method'  => 'POST',
        'content' => $sendParamsStrJson,                
        'header'=>  'Content-Type: application/json'
      )
    );                          
    $myContext = stream_context_create($sendOptions);            
    $myBodyReturn = file_get_contents($url, false, $myContext); 
}  

执行后触发错误:Failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden

GET方式(大文本触发400 Bad Request错误)

代码分支实现:

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 . "?" . $sendParamsQuery);                        
}
var_dump($myBodyReturn);          

处理大文本/HTML内容时触发错误:Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request,推测是GET请求长度超限导致。

2. 尝试CURL POST+JSON仍触发403错误

改用CURL实现POST+JSON请求,代码如下:

$url = "https://translation.googleapis.com/language/translate/v2";
$sendParamsArr = array(
    "key" => "my key" 
    ,
    "source" => 'en-us'
    ,
    "target" => 'da-dk' 
    ,
    "q" => 'smaller amount of <strong>content</strong> to translate'
);                                                  
$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(
    'Content-Type: application/json',
    'Content-Length: ' . 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);

执行后仍返回403错误。

3. 当前状态与疑问

目前仅GET请求可正常处理短文本内容,但无法应对大篇幅的文本/HTML内容。由于GET请求能正常工作,排除API密钥无效的可能,求可行的解决思路。

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:37:05