使用RobotFramework发送POST请求时遇com.fasterxml.jackson.core.JsonParseException异常
问题分析与解决
错误原因
从请求日志可以明确看到:你的POST请求header声明了Content-Type=application/json,但实际发送的请求体是form-urlencoded格式(如Item+Lot+Check+%28Y%2FN%29=N&Lot+Master=...),服务器端的Jackson解析器期望接收JSON格式数据,因此抛出JsonParseException。
这是因为Robot Framework的POST On Session关键字使用data=${body}参数时,会自动将Python字典转换为表单编码字符串,而非JSON字符串,和header声明的格式不匹配。
修复方案
有两种直接可行的解决方式:
方式1:用json参数替代data
POST On Session支持json参数,会自动将字典序列化为JSON字符串,同时自动设置正确的Content-Type(可不用手动指定header中的该字段):
TC2: Testing_createDict ${auth}= Create List Bxxxxxx xxxxxxxxxxxx Create Session mysession ${base_url} auth=${auth} ${entry}= Create Dictionary Lot Status Code=C Item Number=95544403 Lot Expiration Date=09222021 Branch Plant=QIO Lot Description=BSIC-2022-001 Lot Number=185 ${lot master}= Create List ${entry} ${body}= Create Dictionary Item Lot Check (Y/N)=N Lot Master=${lot master} ${response}= POST On Session mysession /jderest/orchestrator/58_XXXXX_XXXX_ORCH json=${body} Log To Console ${response.status_code}
方式2:手动将字典转为JSON字符串后用data参数
如果需要手动控制格式,可先用Convert To Json关键字把字典转成JSON字符串,再传入data参数,同时保留Content-Type header:
TC2: Testing_createDict ${auth}= Create List Bxxxxxx xxxxxxxxxxxx Create Session mysession ${base_url} auth=${auth} ${entry}= Create Dictionary Lot Status Code=C Item Number=95544403 Lot Expiration Date=09222021 Branch Plant=QIO Lot Description=BSIC-2022-001 Lot Number=185 ${lot master}= Create List ${entry} ${body}= Create Dictionary Item Lot Check (Y/N)=N Lot Master=${lot master} ${json_body}= Convert To Json ${body} ${header}= Create Dictionary Content-Type=application/json ${response}= POST On Session mysession /jderest/orchestrator/58_XXXXX_XXXX_ORCH data=${json_body} headers=${header} Log To Console ${response.status_code}
验证要点
修改后查看请求日志,确认请求体是标准JSON格式(如{"Item Lot Check (Y/N)": "N", "Lot Master": [{"Lot Status Code": "C", ...}]}),而非表单编码格式,即可解决解析异常。
内容的提问来源于stack exchange,提问作者vineesh mohan
相关产品推荐
相关产品推荐

