首页 文章

如何使用Curl从终端/命令行发布JSON数据到测试Spring REST?

提问于
浏览
2218

我使用Ubuntu并在其上安装了Curl . 我想用Curl测试我的Spring REST应用程序 . 我在Java端编写了我的POST代码 . 但是,我想用Curl测试它 . 我正在尝试发布JSON数据 . 示例数据如下:

{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}

我用这个命令:

curl -i \
    -H "Accept: application/json" \
    -H "X-HTTP-Method-Override: PUT" \
    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
    http://localhost:8080/xx/xxx/xxxx

它返回此错误:

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT

错误描述如下:

服务器拒绝了此请求,因为请求实体的格式不受所请求方法所请求的资源支持() .

Tomcat日志:“POST / ui / webapp / conf / clear HTTP / 1.1”415 1051

关于Curl命令的正确格式的任何想法?

EDIT:

这是我的Java端PUT代码(我测试了GET和DELETE,它们有效)

@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
    configuration.setName("PUT worked");
    //todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return configuration;
}

17 回答

  • 65

    派对有点晚了,但是我没有看到这个,所以在这里,你也可以将你的json放在一个文件中并通过标准输入使用--file-upload选项将其传递给curl,如下所示:

    echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -
    
  • 90

    对于Windows,使用 -d 值的单引号对我不起作用,但在更改为双引号后它确实有效 . 此外,我需要在大括号内转义双引号 .

    也就是说,以下不起作用:

    curl -i -X POST -H "Content-Type: application/json" -d '{"key":"val"}' http://localhost:8080/appname/path
    

    但以下工作:

    curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path
    
  • 33

    例如,创建一个JSON文件params.json,并将此内容添加到它:

    [
        {
            "environment": "Devel",
            "description": "Machine for test, please do not delete!"
        }
    ]
    

    然后运行此命令:

    curl -v -H "Content-Type: application/json" -X POST --data @params.json -u your_username:your_password http://localhost:8000/env/add_server
    
  • 40

    您需要将content-type设置为application / json . 但是-d发送了Content-Type application/x-www-form-urlencoded ,这在Spring方面是不被接受的 .

    curl man page,我想你可以使用-H

    -H "Content-Type: application/json"
    

    完整示例:

    curl --header "Content-Type: application/json" \
      --request POST \
      --data '{"username":"xyz","password":"xyz"}' \
      http://localhost:3000/api/login
    

    -H--header 的缩写, -d--data 的缩写)

    请注意,如果使用 -d ,则 -request POST 是可选的,因为 -d 标志表示POST请求 .


    在Windows上,情况略有不同 . 查看评论主题 .

  • 12

    这对我来说效果很好,另外还使用BASIC身份验证:

    curl -v --proxy '' --basic -u Administrator:password -X POST -H "Content-Type: application/json"
            --data-binary '{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}'
            http://httpbin.org/post
    

    当然,如果没有SSL和已检查的证书,则不应使用BASIC身份验证 .

    我今天再次遇到这个问题,使用Cygwin的cURL 7.49.1 for Windows ...当使用带有JSON参数的 --data--data-binary 时,cURL感到困惑,并将JSON中的 {} 解释为URL模板 . 添加 -g 参数以关闭cURL globbing修复了该问题 .

    另见Passing a URL with brackets to curl .

  • 11

    尝试将您的数据放在一个文件中,比如 body.json ,然后使用

    curl -H "Content-Type: application/json" --data @body.json http://localhost:8080/ui/webapp/conf
    
  • 24

    我遇到了同样的问题 . 我可以通过指定来解决它

    -H "Content-Type: application/json; charset=UTF-8"
    
  • 29

    使用CURL Windows,试试这个:

    curl -X POST -H "Content-Type:application/json" -d "{\"firstName\": \"blablabla\",\"lastName\": \"dummy\",\"id\": \"123456\"}" http-host/_ah/api/employeeendpoint/v1/employee
    
  • 16

    这对我有用:

    curl -H "Content-Type: application/json" -X POST -d @./my_json_body.txt http://192.168.1.1/json
    
  • 17

    这对我很有用 .

    curl -X POST --data @json_out.txt http://localhost:8080/
    

    哪里,

    -X 表示http动词 .

    --data 表示要发送的数据 .

  • 3487

    如果您正在针对RESTful接口测试大量JSON发送/响应,您可能需要查看适用于Chrome的Postman插件(允许您手动定义Web服务测试)及其基于Node.js的Newman命令-line companion(允许你自动化测试邮件测试的"collections" . )免费和开放!

  • -2

    您可以将所需格式的扩展名作为URL的末尾传递 . 喜欢http://localhost:8080/xx/xxx/xxxx .json

    要么

    http://localhost:8080/xx/xxx/xxxx .xml

    注意:您需要在pom中添加jackson和jaxb maven依赖项 .

  • 71

    我使用以下格式来测试Web服务器 .

    use -F 'json data'
    

    我们假设这个JSON dict格式:

    {
        'comment': {
            'who':'some_one',
            'desc' : 'get it'
        }
    }
    

    完整的例子

    curl -XPOST your_address/api -F comment='{"who":"some_one", "desc":"get it"}'
    
  • 13

    您可以使用Postman及其直观的GUI来汇编 cURL 命令 .

    • 安装并启动 Postman

    • 输入您的网址,帖子正文,请求 Headers 等 .

    • 点击 Code

    • 从下拉列表中选择 cURL

    • 复制并粘贴 cURL 命令

    注意:在下拉列表中有几个自动请求生成选项,这就是为什么我认为我的帖子首先是必要的 .

  • 7

    你可能会发现有用的东西:https://github.com/micha/resty

    它是CURL的包装器,简化了命令行REST请求 . 您将其指向您的API endpoints ,它为您提供PUT和POST命令 . (从主页改编的例子)

    $ resty http://127.0.0.1:8080/data #Sets up resty to point at your endpoing
    $ GET /blogs.json                  #Gets http://127.0.0.1:8080/data/blogs.json
                                       #Put JSON
    $ PUT /blogs/2.json '{"id" : 2, "title" : "updated post", "body" : "This is the new."}'
                                       # POST JSON from a file
    $ POST /blogs/5.json < /tmp/blog.json
    

    此外,通常仍需要添加内容类型标头 . 但是,您可以执行一次设置默认的每站点每个方法的添加配置文件:Setting default RESTY options

  • 12

    HTTPiecurl 的推荐替代品,因为你可以做到

    $ http POST http://example.com/some/endpoint name=value name1=value1
    

    默认情况下它会说JSON,并且会处理为您设置必要的标头以及将数据编码为有效的JSON . 还有:

    Some-Header:value
    

    对于 Headers ,和

    name==value
    

    用于查询字符串参数 . 如果您有大量数据,您也可以从文件中读取它,如果它是JSON编码的:

    field=@file.txt
    
  • 453

    它对我有用:

    curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"id":100}' http://localhost/api/postJsonReader.do
    

    很高兴映射到Spring控制器:

    @RequestMapping(value = "/postJsonReader", method = RequestMethod.POST)
    public @ResponseBody String processPostJsonData(@RequestBody IdOnly idOnly) throws Exception {
            logger.debug("JsonReaderController hit! Reading JSON data!"+idOnly.getId());
            return "JSON Received";
    }
    

    IdOnly 是一个带有id属性的简单POJO .

相关问题