如何用Groovy发送正确JSON请求体的POST请求并解决500错误?
Fixing 500 Error in Groovy POST Request with JSON Body
我看了你遇到的问题——Postman里能正常发送的JSON请求,换成Groovy代码写就返回500错误,核心原因是你代码里的请求体和Postman的数据类型不匹配,还漏了几个必填字段。咱们一步步来修正:
问题点分析
- 布尔值类型错误:你代码里把
fromSoo、isElectronicSign写成了字符串'true',但Postman的请求里是原生布尔值true,API大概率会严格校验字段类型,这直接导致参数不合法。 - 必填字段缺失:Postman的JSON里包含
copies、responseTo这两个字段,你代码里完全没加,API可能要求这些字段为必填项。 - 数据类型不一致:
apps在Postman里是字符串"5",你代码里写的是数字5,如果API期望字符串类型,这里也会触发参数错误。 - 嵌套结构(可选):如果你的测试场景需要带附件和审核列表数据,得正确构造嵌套对象数组;如果是测试空数组场景,确保API允许空值即可。
修正后的Groovy代码
import groovyx.net.http.RESTClient def rest = new RESTClient('http://logicased-mog.service.btlab.ru/') // 严格匹配Postman的JSON结构和数据类型 def requestBody = [ fromSoo: true, attachments: [ [attachmentNodeRef: "workspace://SpacesStore/2c300b5a-8646-45ea-afc4-c8a4a6a2db55", attachmentCategory: "1"], [attachmentNodeRef: "workspace://SpacesStore/d71d31f7-c1fe-434a-8774-6dbb77bd135b", attachmentCategory: "2"], [attachmentNodeRef: "workspace://SpacesStore/faf06ad7-6707-4926-8c45-0e4d1d9b482e", attachmentCategory: "3"] ], signer: "qqqe", executor: "qqqw", isElectronicSign: true, shortDescription: "short", sheetsNumber: 3, copies: "4", responseTo: "workspace://SpacesStore/0fc89bec-7b62-4862-a90b-311bd2c0a447", note: "note", reviewList: [ [stageItemMember: "kol", decisionTime: "15:15:15", decisionDate: "11-12-2020"], [stageItemMember: "qqqq", decisionTime: "11", decisionDate: "13-12-2020"], [stageItemMember: "qqq7", decisionTime: "18", decisionDate: "14-12-2020"] ], NodeRef: "workspace://SpacesStore/990c4554-5499-44fe-9783-e3fbdb458d31", apps: "5" ] try { def response = rest.post( path: 'alfresco/s/mog/outgoing/createOutgoing', headers: [Authorization: "user1 user1"], body: requestBody, requestContentType: 'application/json' ) println "请求成功,状态码:${response.status}" println "响应数据:${response.responseData}" return response.contentType } catch (groovyx.net.http.HttpResponseException e) { // 捕获异常,打印详细错误信息,方便排查 println "请求失败,状态码:${e.statusCode}" println "错误响应:${e.response.data}" throw e }
额外注意事项
- Basic认证优化:如果你的API使用Basic身份验证,更规范的写法是调用
rest.auth.basic('user1', 'user1'),而不是手动构造Authorization header,避免格式错误。 - 异常排查:添加异常捕获后,你能看到API返回的具体错误信息(比如哪个字段不合法),而不是只看到500状态码,这会大大提升排查效率。
- 空值场景测试:如果需要测试
attachments或reviewList为空的情况,直接设为[]即可,但要确保API允许这些字段为空。
内容的提问来源于stack exchange,提问作者Alevtina
相关产品推荐
相关产品推荐

