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

Symfony调用Google Translate API v2批量翻译报400错误的解决咨询

解决Symfony HttpClient调用Google Translate API批量翻译的400错误

问题根源在于两个关键点:

  1. Symfony HttpClient默认会把body数组编码为application/x-www-form-urlencoded格式,导致q数组被转换为q[]=xxx的表单参数形式,不符合Google Translate API期望的JSON数组格式;
  2. 请求头的键名错误,正确的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:10:17