使用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
相关产品推荐
相关产品推荐

