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

在AppScript中正常调用Cloud Natural Language classifyText API

问题现象

调用Google自然语言处理的analyzeSentiment接口时,以下代码可正常运行:

function analyzeText() {
    
  var apiKey = 'myapi';

  var text = 'I really love dogs!';

  var requestUrl = ['https://language.googleapis.com/v1/documents:analyzeSentiment?key=', apiKey].join(
    ''
  );

  // 其他可用接口提示:
  // documents:analyzeEntities 用于实体分析
  // documents:analyzeSyntax 用于句法分析

  var data = {
    document: {
      language: 'en-us',
      type: 'PLAIN_TEXT',
      content: text,
    },
    encodingType: 'UTF8',
  };

  var options = {
    method: 'POST',
    contentType: 'application/json',
    payload: JSON.stringify(data),
  };

  var response = UrlFetchApp.fetch(requestUrl, options);

  var data = JSON.parse(response);

  Logger.log(data);
}

仅修改requestUrl为classifyText接口地址后,接口返回400错误,错误信息如下:

Exception: Request failed for https://language.googleapis.com returned code 400. Truncated server response: {
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"encodingType\": Cannot find field.",
    "status": "I... (use muteHttpExceptions option to examine full response)
analyzeText @ Code.gs:30
问题原因

classifyText接口的请求体规范和情感分析接口存在差异:

  • encodingType参数仅适用于需要返回文本字符偏移量的接口(包括情感分析、实体分析、句法分析接口),作用是告知接口计算偏移量时遵循的编码规则
  • 文本分类接口classifyText不需要返回偏移量信息,请求体不支持encodingType字段,传入该字段会直接触发参数校验失败,返回400错误

额外注意:classifyText接口对传入文本有最低长度要求,文本少于20个token时同样会返回错误,测试时需要使用长度符合要求的文本。

修复方案

构造请求参数时删除encodingType字段即可,适配分类接口的代码示例:

function classifyText() {
  var apiKey = 'myapi';
  // 文本长度需满足至少20个token的要求
  var text = 'I really love dogs, I have raised two golden retrievers at home for three years, they are very friendly to children and always accompany me when I go out for hiking on weekends.';
  var requestUrl = ['https://language.googleapis.com/v1/documents:classifyText?key=', apiKey].join('');

  var data = {
    document: {
      language: 'en-us',
      type: 'PLAIN_TEXT',
      content: text,
    }
    // 移除classifyText不支持的encodingType字段
  };

  var options = {
    method: 'POST',
    contentType: 'application/json',
    payload: JSON.stringify(data),
    // 调试阶段可开启该配置查看完整错误响应
    // muteHttpExceptions: true
  };

  var response = UrlFetchApp.fetch(requestUrl, options);
  var resData = JSON.parse(response);
  Logger.log(resData);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 02:15:25