How do I POST JSON data with cURL?

后端 未结 24 2567
刺人心
刺人心 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:44

    Here is another way to do it, if you have dynamic data to be included.

    #!/bin/bash
    
    version=$1
    text=$2
    branch=$(git rev-parse --abbrev-ref HEAD)
    repo_full_name=$(git config --get remote.origin.url | sed 's/.*:\/\/github.com\///;s/.git$//')
    token=$(git config --global github.token)
    
    generate_post_data()
    {
      cat <<EOF
    {
      "tag_name": "$version",
      "target_commitish": "$branch",
      "name": "$version",
      "body": "$text",
      "draft": false,
      "prerelease": false
    }
    EOF
    }
    
    echo "Create release $version for repo: $repo_full_name branch: $branch"
    curl --data "$(generate_post_data)" "https://api.github.com/repos/$repo_full_name/releases?access_token=$token"
    
    0 讨论(0)
  • 2020-11-22 00:44

    If you configure the SWAGGER to your spring boot application, and invoke any API from your application there you can see that CURL Request as well.

    I think this is the easy way of generating the requests through the CURL.

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

    I just run into the same problem. I could solve it by specifying

    -H "Content-Type: application/json; charset=UTF-8"
    
    0 讨论(0)
  • 2020-11-22 00:45

    You can use postman to convert to CURL

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

    Use -d option to add payload

    curl -X POST \
    http://<host>:<port>/<path> \
    -H 'Accept: application/json' \
    -H 'Content-Type: application/json' \
    -d '{
    "foo": "bar",
    "lorem": "ipsum"
    }'
    

    In addition:

    use -X POST to use POST method

    use -H 'Accept: application/json' to add accept type header

    use -H 'Content-Type: application/json' to add content type header

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

    This worked well for me.

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

    Where,

    -X Means the http verb.

    --data Means the data you want to send.

    0 讨论(0)
提交回复
热议问题