Windows下使用CURL发送JSON格式POST请求出现解析错误的问题求助
我之前在Windows批处理里用curl发JSON POST请求的时候,也踩过一模一样的坑!这些错误本质上是CMD对特殊字符的处理逻辑,加上curl默认的globbing功能在搞鬼,给你两个实用的解决办法:
解决办法一:修正命令行转义,关闭curl的Globbing功能
Windows CMD里双引号需要用^转义,而且curl默认会把{}当作通配符解析(也就是globbing),这会直接把你的JSON结构拆成一堆无效参数,导致出现“无法解析主机”的错误。所以我们要做两件事:
- 加**
-g参数**关闭curl的globbing功能,避免它解析JSON里的{} - 把整个JSON用外层双引号包裹,内部的每个双引号前加
^转义(CMD的转义规则)
修正后的完整命令:
curl.exe -g -X POST "https://api.inxpress.com/imcs_gateway/c_1/" -H "Content-Type: application/json" -d "{^ \"request_id\":\"pm77\",^ \"request_time\":\"2020-12-24\",^ \"account\":\"accountname\",^ \"password\":\"apikey\",^ \"gateway\":\"UK\",^ \"carrierCode\":\"C_1\",^ \"origin\":{^ \"city\":\"ROCHDALE\",^ \"postal_code\":\"OL16 5DB\",^ \"country\":\"GB\"^ },^ \"destination\":{^ \"city\":\"Bellville\",^ \"postal_code\":\"7530\",^ \"country\":\"ZA\"^ },^ \"product_code\":\"P\",^ \"content_type\":\"WPX\",^ \"weight_unit\":\"kg\",^ \"dimension_unit\":\"cm\",^ \"currency\":\"GBP\",^ \"insured_value\":\"3.00\",^ \"dutiable\":true,^ \"commercial_value\":\"5.00\",^ \"pieces\":[^ {^ \"name\":\"Piece 1\",^ \"weight\":5.0,^ \"height\":8.0,^ \"depth\":12.0,^ \"width\":12.0,^ \"quantity\":1,^ \"custom_value\":10.0^ }^ ]^ }"
注:每行末尾的^是CMD的换行续行符,只是为了让命令更易读,你也可以把所有内容写到一行里
解决办法二:把JSON写入文件,用文件作为请求体(更推荐)
如果JSON结构复杂,命令行转义很容易出错,最省心的方式是把JSON内容单独存成一个文件:
- 创建一个
request.json文件,内容就是你的原始JSON(不需要任何转义):
{ "request_id":"pm77", "request_time":"2020-12-24", "account":"accountname", "password":"apikey", "gateway":"UK", "carrierCode":"C_1", "origin":{ "city":"ROCHDALE", "postal_code":"OL16 5DB", "country":"GB" }, "destination":{ "city":"Bellville", "postal_code":"7530", "country":"ZA" }, "product_code":"P", "content_type":"WPX", "weight_unit":"kg", "dimension_unit":"cm", "currency":"GBP", "insured_value":"3.00", "dutiable":true, "commercial_value":"5.00", "pieces":[ { "name":"Piece 1", "weight":5.0, "height":8.0, "depth":12.0, "width":12.0, "quantity":1, "custom_value":10.0 } ] }
- 用curl命令读取这个文件作为请求体:
curl.exe -X POST "https://api.inxpress.com/imcs_gateway/c_1/" -H "Content-Type: application/json" -d @request.json
这种方法完全避开了命令行转义的麻烦,结构清晰,后期修改JSON也更方便。
内容的提问来源于stack exchange,提问作者Stephen Bouffe
相关产品推荐
相关产品推荐

