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

Groovy使用RESTClient发送JSON PUT请求遇EncoderRegistry.encodeForm()错误

Groovy RESTClient PUT请求JSON格式修复方案

问题重现

要通过Groovy的RESTClient发送Content-Type为JSON的PUT请求,原代码如下:

def params = ["content": listOfSymbols.join(","), "privacy": "U", "collection": collection, "asOfDate": todaysDate, "sync": "Y", "postingId": id]
// 注:listOfSymbols是ArrayList,collection、todaysDate、id为变量
// 预期请求体是JSON对象数组

def jsonBody = []
jsonBody.add(JsonOutput.toJson(params))

def response = restClient.put(
            path: sPath,
            headers: ["Content-Type": 'application/json', "Authorization": "Bearer ${token}", charset: 'UTF-8'],
            body: jsonBody,
            requestContentType: URLENC
    )

执行后报错:

Caught generic exception: groovy.lang.MissingMethodException: No signature of method: groovyx.net.http.EncoderRegistry.encodeForm() is applicable for argument types: (ArrayList, groovyx.net.http.ContentType) values: [[{"content":"abc,pqr","privacy":"U","collection":"test1","asOfDate":"2024-06-04","sync":"Y","postingId":"1"}], ...]

错误原因

  1. 请求内容类型配置错误:requestContentType: URLENC指定了表单编码(application/x-www-form-urlencoded),但实际要发送JSON格式,客户端尝试把ArrayList按表单规则编码,而EncoderRegistry没有对应处理逻辑,导致方法找不到。
  2. 请求体构建错误:手动调用JsonOutput.toJson(params)把单个对象转成JSON字符串,再加入数组,最终请求体是JSON字符串组成的数组,而非预期的JSON对象数组。

修复方案

步骤1:修正请求内容类型

将requestContentType改为ContentType.JSON(需确保导入groovyx.net.http.ContentType),让RESTClient自动处理JSON序列化。

步骤2:正确构建JSON数组请求体

直接将params对象加入列表,无需手动调用JsonOutput.toJson,RESTClient会自动把对象数组序列化为JSON格式。

修复后完整代码

// 确保导入ContentType
import groovyx.net.http.ContentType

def params = ["content": listOfSymbols.join(","), "privacy": "U", "collection": collection, "asOfDate": todaysDate, "sync": "Y", "postingId": id]

// 直接构建对象数组,无需手动转JSON字符串
def jsonBody = [params]

def response = restClient.put(
            path: sPath,
            headers: ["Authorization": "Bearer ${token}", charset: 'UTF-8'],
            body: jsonBody,
            requestContentType: ContentType.JSON
    )

补充说明

  • 如果需要多个JSON对象,直接往jsonBody里添加更多对象即可,比如jsonBody.add(anotherParams)。
  • 配置requestContentType: ContentType.JSON后,RESTClient会自动设置Content-Type: application/json请求头,无需手动在headers中添加(若手动添加也不会冲突)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 21:33:26