Symfony调用Google Translate API v2批量翻译报400错误的解决咨询
解决Symfony HttpClient调用Google Translate API批量翻译的400错误
问题根源在于两个关键点:
- Symfony HttpClient默认会把
body数组编码为application/x-www-form-urlencoded格式,导致q数组被转换为q[]=xxx的表单参数形式,不符合Google Translate API期望的JSON数组格式; - 请求头的键名错误,正确的Content-Type头键应为
Content-Type而非ContentType。
以下两种修改方式均可解决问题:
方式一:手动处理JSON请求体
将请求体数组转为JSON字符串,并修正请求头配置:
$textArray = ["this is my text", "my text is amazing"]; $bodyData = [ 'q' => $textArray, 'target' => $targetLocale, 'format' => $format, 'source' => $locale, 'model' => 'base', 'key' => $this->parameterBag->get('google_api_key') ]; $options = [ 'body' => json_encode($bodyData), 'headers' => [ 'Content-Type' => 'application/json' ] ]; $response = $this->client->request( 'POST', $this->parameterBag->get('google_translate_api.v2.translate_path'), $options );
方式二:使用Symfony HttpClient的json选项
利用框架内置的json选项,自动完成JSON编码和请求头设置,代码更简洁:
$textArray = ["this is my text", "my text is amazing"]; $options = [ 'json' => [ 'q' => $textArray, 'target' => $targetLocale, 'format' => $format, 'source' => $locale, 'model' => 'base', 'key' => $this->parameterBag->get('google_api_key') ] ]; $response = $this->client->request( 'POST', $this->parameterBag->get('google_translate_api.v2.translate_path'), $options );
内容的提问来源于stack exchange,提问作者Varg
相关产品推荐
相关产品推荐

