How do I POST JSON data with cURL?

后端 未结 24 2594
刺人心
刺人心 2020-11-21 23:56

I use Ubuntu and installed cURL on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am

相关标签:
24条回答
  • 2020-11-22 00:27

    This worked for me for on Windows10

    curl -d "{"""owner""":"""sasdasdasdasd"""}" -H "Content-Type: application/json" -X  PUT http://localhost:8080/api/changeowner/CAR4
    
    0 讨论(0)
  • 2020-11-22 00:30

    For Windows, having a single quote for the -d value did not work for me, but it did work after changing to double quote. Also I needed to escape double quotes inside curly brackets.

    That is, the following did not work:

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

    But the following worked:

    curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path
    
    0 讨论(0)
  • 2020-11-22 00:32

    I am using the below format to test with a web server.

    use -F 'json data'
    

    Let's assume this JSON dict format:

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

    Full example

    curl -XPOST your_address/api -F comment='{"who":"some_one", "desc":"get it"}'
    
    0 讨论(0)
  • 2020-11-22 00:35

    You need to set your content-type to application/json. But -d sends the Content-Type application/x-www-form-urlencoded, which is not accepted on Spring's side.

    Looking at the curl man page, I think you can use -H:

    -H "Content-Type: application/json"
    

    Full example:

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

    (-H is short for --header, -d for --data)

    Note that -request POST is optional if you use -d, as the -d flag implies a POST request.


    On Windows, things are slightly different. See the comment thread.

    0 讨论(0)
  • 2020-11-22 00:35

    Try to put your data in a file, say body.json and then use

    curl -H "Content-Type: application/json" --data @body.json http://localhost:8080/ui/webapp/conf
    
    0 讨论(0)
  • 2020-11-22 00:35

    This worked for me:

    curl -H "Content-Type: application/json" -X POST -d @./my_json_body.txt http://192.168.1.1/json
    
    0 讨论(0)
提交回复
热议问题