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

GAS向自有服务器发送HTTP请求无法接收响应求助

GAS发送HTTP POST请求无法接收响应问题排查

使用Google Apps Script(GAS)向自有服务器发送HTTP POST请求时无法接收响应,报错信息为:

Error:  Unexpected error: http://examle.com:9119

经测试确认:

  • 向Google服务器发送请求可正常接收响应;
  • 使用Postman向自有服务器发送相同请求可成功获取响应;
  • 服务器日志显示已收到GAS的请求,但如果在返回响应前延迟5秒,GAS会在5秒后触发报错,推测问题出在GAS接收响应环节。

相关代码

GAS代码

function sendPostRequest(data) {
  // target server
  const url = 'http://examle.com:9119';
  
  const body = JSON.stringify({ title: 'foo', body: 'bar', userId: 1 });

  const options = {
    'method': 'POST',
    'payload': body,
    'headers': {
      'Content-Type': 'application/json; charset=UTF-8',
      'Accept': '*/*',
    },
    'muteHttpExceptions': false
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    console.log(response.getHeaders()); // Log the response body
    return response;
  } catch (error) {
    console.error('Error: ', error.message);
    console.error('Stack trace: ', error.stack);
  }
}

报错信息

Error:  Unexpected error: http://examle.com:9119

自有服务器相关代码

private static void dataBack(@Nullable String result, HttpServletResponse response) {
    try {
        response.setContentType("application/json; charset=UTF-8");
        OutputStream out = response.getOutputStream();
        if (result == null) {
            out.write(UnknownErrorMessage.getBytes());
            out.flush();
            out.close();
            return;
        }

        out.write(result.getBytes());
        out.flush();
        out.close();
    }
    catch (Exception ex) {
        Logger.info("dataBack error: " + ex.getMessage());
        handleException(ex);
    }
}

排查方向与解决方案

1. 调整UrlFetchApp超时设置

GAS的UrlFetchApp默认超时为5秒,这和你测试的延迟5秒触发报错完全匹配,而Postman无此默认限制。需在请求选项中显式设置更长超时:

const options = {
  // 保留原有配置
  'timeout': 30000 // 设置为30秒,单位毫秒,可按需调整
};

2. 修复服务器响应编码问题

原服务器代码中getBytes()依赖系统默认编码,可能导致响应内容编码不一致,GAS无法解析。修改为UTF-8编码:

// 替换两处getBytes()调用
out.write(UnknownErrorMessage.getBytes(StandardCharsets.UTF_8));
// ...
out.write(result.getBytes(StandardCharsets.UTF_8));

同时建议添加Content-Length响应头,帮助GAS判断响应完整性:

response.setContentLength(result.getBytes(StandardCharsets.UTF_8).length);

3. 开启调试模式获取详细错误

将muteHttpExceptions设为true,即使请求返回非2xx状态码,也能获取响应详情,便于排查:

const options = {
  // 保留原有配置
  'muteHttpExceptions': true
};

并在catch块中补充日志:

catch (error) {
  if (error.response) {
    console.error('响应状态码:', error.response.getResponseCode());
    console.error('响应内容:', error.response.getContentText());
  }
  console.error('Error: ', error.message);
}

4. 检查服务器网络限制

确认服务器防火墙、反向代理(如Nginx/Apache)是否对响应返回做了限制,比如拦截来自GAS的请求响应、设置过短的响应超时时间,可查看服务器代理日志验证响应是否正常发出。

内容的提问来源于stack exchange,提问作者kensho hanano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 05:43:12