使用WP_Http_Curl调用IBM文档翻译API遇415媒体类型错误求助
解决IBM Document Translator API返回415 Unsupported Media Type的问题
你遇到的415错误核心原因是请求的Content-Type和数据格式不匹配IBM Document Translator的要求。虽然你设置了text/plain,但文档翻译API需要通过multipart/form-data格式来上传文件,而不是直接将文件内容作为text/plain的请求体发送。
你的代码核心问题分析
- 你把文件内容直接放到
file字段,并且手动设置了Content-Type: text/plain,但API期望的是通过multipart表单上传完整文件,同时附带其他参数(比如filename、model_id等)。 - WP的
wp_remote_request在处理数组形式的body时,会自动处理multipart编码,但前提是文件字段的格式正确。
修正后的代码示例
$filename = ABSPATH . 'wp-content/uploads/sample.txt'; $auth = '你的Base64编码API密钥'; // 确保这里是"apikey:你的实际密钥"的Base64结果 // 构建符合要求的multipart表单数据,文件字段用CURLFile对象处理 $postBody = array( 'file' => new CURLFile($filename, 'text/plain', 'sample.txt'), 'model_id' => 'en-fr', ); $response = wp_remote_request( 'https://api.jp-tok.language-translator.watson.cloud.ibm.com/instances/9ccfc671-1c75-40b6-ad45-b46ae4b53979/v3/documents?version=2018-05-01', array( 'method' => 'POST', 'body' => $postBody, 'headers' => array( 'Authorization' => 'Basic ' . $auth, // 无需手动设置Content-Type,WP会自动生成multipart/form-data的正确头部 'Accept' => 'application/json' // API默认返回JSON,用这个更便于后续解析 ) ) ); print_r($response);
关键修改点说明
- 文件字段处理:使用
CURLFile对象替代直接传文件内容,WP的HTTP客户端会自动识别这是文件上传字段,生成符合要求的multipart编码。 - Content-Type头部:移除手动设置的
text/plain,让WP根据body数组自动生成multipart/form-data头部(包含正确的boundary分隔符)。 - Accept头部:API默认返回JSON格式响应,设置
application/json更合理,方便后续处理返回结果。
兼容旧PHP版本的替代方案
如果你的PHP版本低于5.5(不推荐使用旧版本),可以用以下方式替代CURLFile:
'file' => '@' . $filename . ';filename=sample.txt;type=text/plain'
额外检查事项
- 确认
$auth是apikey:你的IBM API密钥字符串经过Base64编码后的结果。 - 确保
sample.txt文件存在,且PHP进程有读取该文件的权限。
内容的提问来源于stack exchange,提问作者nishan
相关产品推荐
相关产品推荐

