By kamaci


2011-08-24 08:51:11 8 Comments

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 trying to post a JSON data. Example data is like this:

{"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}

I use this command:

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

It returns this error:

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

The error description is this:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

Tomcat log: "POST /ui/webapp/conf/clear HTTP/1.1" 415 1051

What is the right format of the cURL command?

This is my Java side PUT code (I have tested GET and DELETE and they work):

@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;
}

24 comments

@YouAreAwesome 2020-04-28 13:54:30

I know, a lot has been answered to this question but wanted to share where I had the issue of:

curl -X POST http://your-server-end-point -H "Content-Type: application/json" -d @path-of-your-json-file.json

See, I did everything right, Only one thing - "@" I missed before the JSON file path.

I found one relevant go-to document on internet - https://gist.github.com/subfuzion/08c5d85437d5d4f00e58

Hope that might help the few. thanks

@AnilkumarReddy 2019-11-28 12:06:54

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.

@sudhanshu srivastava 2019-07-09 09:58:01

This worked for me for on Windows10

curl -d "{"""owner""":"""sasdasdasdasd"""}" -H "Content-Type: application/json" -X  PUT http://localhost:8080/api/changeowner/CAR4

@Anand Rockzz 2019-08-06 06:02:43

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"

@Abhimanyu 2020-04-09 12:57:25

You saved my life!

@byte mamba 2019-05-30 06:43:36

You can use postman to convert to CURLenter image description here

enter image description here

@vibs2006 2019-06-17 09:37:22

Thanks a lot @forever-LA it was a life saver tip for me

@Pranay Kumar 2019-05-27 11:40:28

Please check this tool. It helps you to easily create curl snippets.

curl -XGET -H "Accept: application/json" -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"

@Sma Ma 2019-04-13 20:06:36

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

@Suresh 2020-06-01 14:16:27

I tried to use it but getting {"errors":["no data provided"]} error.

@niken 2017-06-13 19:41:11

You could also put your JSON content in a file and pass it to curl using the --file-upload option via standard input, like this:

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

@tosh 2017-11-08 12:45:59

HTTPie is a recommended alternative to curl because you can do just

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

It speaks JSON by default and will handle both setting the necessary header for you as well encoding data as valid JSON. There is also:

Some-Header:value

for headers, and

name==value

for query string parameters. If you have a large chunk of data, you can also read it from a file have it be JSON encoded:

 [email protected]

@Saurabh Oza 2018-07-16 09:57:33

You can pass the extension of the format you want as the end of the url. like http://localhost:8080/xx/xxx/xxxx.json

or

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

Note: you need to add jackson and jaxb maven dependencies in your pom.

@Mark Stosberg 2018-08-23 14:01:31

That would only work if the server-side accepted the URLS with those extensions.

@Sean Patrick Floyd 2011-08-24 09:12:29

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.

@Sean Patrick Floyd 2011-08-24 09:43:35

@kamaci I don't think you need to remove -d, just use -H in addition.

@kamaci 2011-08-24 09:48:23

I try that: 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 localhost:8080/ui/webapp/conf

@Sean Patrick Floyd 2011-08-24 09:59:11

@kamaci OK then I'm afraid I can't help you without having access to your server logs. I currently don't have access to any Spring MVC projects. I'd try to look for the http query path in your log file and continue from there. Perhaps you could append a relevant bit of the log to this question.

@hIpPy 2013-09-11 17:34:40

For windows, single quotes around json did not work and I ended up escaping double quotes. curl -X POST -H "Content-Type: application/json" -d "{ \"key1\": \"value1\" }" http://localhost:3000/api/method

@chodorowicz 2014-01-27 11:10:59

For me under Windows I needed to escape quotes using quotes in this format "{ """key1""": """value1""" }". Also this answer: stackoverflow.com/questions/18314796/…

@Sean Patrick Floyd 2014-01-27 12:42:55

@chodorowicz that's awful! I only know that syntax from VB!

@chodorowicz 2014-01-27 20:21:46

@SeanPatrickFloyd Yeah! It's ludicrous. At such moments I'm considering much more seriously moving to *nix system.

@WiteCastle 2014-04-24 18:13:22

I've had issues with POST requests but solved it by capitalized "Application/json" so if you get a 415 error, check the capitalization.

@Silvio Troia 2014-05-14 10:03:42

if you use a model on @RequestBody, remember that it doesn't want a costructor

@Guss 2014-05-26 13:58:25

It is also possible to pipe the JSON data from STDIN by using -d @- as the curl option

@Frozen Flame 2015-01-02 08:20:52

contentType or Content-Type?

@Sean Patrick Floyd 2015-01-02 10:46:04

@FrozenFlame header names are title case with dashes, see RFC. Some frameworks like jquery accept headers in camelCase and translate those internally to Title-Dash, but curl doesn't afaik

@FilBot3 2015-03-20 00:55:18

I had to POST the data without 's around the {}'s. Then it worked. You'd think it'd be one standard wayto do it.

@codersaif 2015-07-20 06:51:42

To use mixed single quotation and double quotation you can use git bash or some other third party provided terminal

@Someone Somewhere 2015-10-07 12:25:14

Why does the windows version of curl require double-quotes around json data?? It's totally ridiculous

@ostrokach 2015-10-18 23:30:10

@Adam Tuttle Why does your comment have so many upvotes? With curl on ubuntu 14.04, you need "Content-Type: application/json", not just "application/json". This wasted a lot of my time...

@Adam Tuttle 2015-11-01 01:23:23

@ostrokach sorry it wasted your time. syntax worked fine for me on OSX when I posted it (haven't retried). Guess it is/was just a platform difference. I imagine the upvotes are from people that it helped.

@Keegan Jay 2017-01-18 07:37:43

Can you put a little note that this might not work on windows? Ctrl-F "Windows" below.

@Sean Patrick Floyd 2017-01-18 13:11:11

@JayKeegan I added a little note but I'm not going to pollute my post with that strange syntax

@Lei Yang 2018-05-17 15:07:01

I face even more strange behaviour when calling this curl command by java Runtime.getRuntime().exec method, in linux I must remove the double quotes. anybody knows why?

@flow2k 2018-07-11 20:35:13

Just like -d or --data defaults to using POST, so does the --data-urlencode option.

@Reginaldo Santos 2019-02-20 20:02:59

I was using -H 'Content-Type: application/json;charset=UTF-8' on linux which shell is UTF-8 .., but strangely removing the charset parameter solved my problem as well.

@riemannzz 2019-06-13 10:14:56

On windows, I managed to single quote the whole parameter, leaving the original json with double quotes, like the "Full example" above: -d '{"username":"xyz","password":"xyz"}'

@Aslam Shaik 2019-07-31 06:03:13

| python -m json.tool add this pipe to get json output in readable format

@Suresh 2020-06-01 14:10:49

When I am trying to use the same format in Linux, I am getting "no data provided" error.

@Eduardo Cerqueira 2016-01-05 23:10:42

As an example, create a JSON file, params.json, and add this content to it:

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

Then you run this command:

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

@kiltek 2017-09-25 12:47:20

You can use Postman with its intuitive GUI to assemble your cURL command.

  1. Install and Start Postman
  2. Type in your URL, Post Body, Request Headers etc. pp.
  3. Click on Code
  4. Select cURL from the drop-down list
  5. copy & paste your cURL command

Note: There are several options for automated request generation in the drop-down list, which is why I thought my post was neccessary in the first place.

@ariestav 2019-03-05 16:31:57

Didn't realize that feature was included in Postman. Thanks for pointing it out!

@venkatnz 2014-06-30 22:12:42

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

@acanby 2016-03-14 23:10:46

FYI - looks like you're missing a closing double quote around the json body

@rodedo 2016-10-17 09:44:11

For me on Windows, the " around the data does not work, no quotes works instead

@rsenna 2018-02-28 19:02:52

If you're using PowerShell, see this answer.

@user3180641 2014-01-10 06:49:46

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"}'

@davenpcj 2013-06-05 23:24:08

This worked well for me, additionally using BASIC authentication:

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

Of course, you should never use BASIC authentication without SSL and a checked certificate.

I ran into this again today, using Cygwin's cURL 7.49.1 for Windows... And when using --data or --data-binary with a JSON argument, cURL got confused and would interpret the {} in the JSON as a URL template. Adding a -g argument to turn off cURL globbing fixed that.

See also Passing a URL with brackets to curl.

@Luis 2012-04-19 16:00:25

It worked for me using:

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

It was happily mapped to the Spring controller:

@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 is a simple POJO with an id property.

@ftexperts 2014-05-23 13:34:21

If you're testing a lot of JSON send/responses against a RESTful interface, you may want to check out the Postman plug-in for Chrome (which allows you to manually define web service tests) and its Node.js-based Newman command-line companion (which allows you to automate tests against "collections" of Postman tests.) Both free and open!

@Amit Vujic 2016-10-16 16:07:00

This worked for me:

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

@Felipe Pereira 2015-07-01 14:31:40

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.

@Software Engineer 2018-01-22 16:05:45

The -X POST is redundant in this example

@Márcio Brener 2014-12-20 23:45:07

Using CURL Windows, try this:

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

@mo-seph 2012-01-12 19:10:58

You might find resty useful: https://github.com/micha/resty

It's a wrapper round CURL which simplifies command line REST requests. You point it to your API endpoint, and it gives you PUT and POST commands. (Examples adapted from the homepage)

$ 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

Also, it's often still necessary to add the Content Type headers. You can do this once, though, to set a default, of add config files per-method per-site: Setting default RESTY options

@Steffen Roller 2011-11-15 15:45:09

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

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

@Typisch 2011-08-24 10:04:24

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

@AmirHd 2013-06-05 11:56:19

checkout the answer on how use CURL and what does different errors mean.

@h2stein 2014-03-24 08:22:40

You probably should use the --data-binary option instead of --data. One would expect that the client sends the data as-is, but --data strips CR und LF from the input.

@Xtreme Biker 2014-06-26 10:26:41

Using cUrl with inline json Strings seems to be a nightmare. There's the need to scape the double quote character. Going with a file like this is nicer.

@Radu Murzea 2015-08-18 11:41:09

It's important to add an @ character before the name of the file, otherwise it won't work. I just spent 20 minutes banging my head at this crap...

@datashaman 2016-12-07 12:37:01

This way you can also run a JSON lint on the file to see if there's an error in parsing the JSON.

@Stomf 2017-06-26 09:28:15

On Windows, you need double quotes around the filename "@body.json"

@Azurespot 2020-05-12 22:09:52

First, THANK YOU, you just saved me days of headache. Also, I'm using Windows 10 and was able to get the @file_name.json without needing quotes. I put the JSON query into a file and used English/Spanish/Chinese in my file query (so no need to set UTF). Here is my final call: curl -H "Ocp-Apim-Subscription-Key: <key>" -H "Content-Type: application/json" --data-binary @body.json "<endpoint>"

@WinEunuuchs2Unix 2020-06-11 01:02:46

Having a separate file for every jason command to pass to --data sounds like a nightmare. Couldn't you just use a here string (<<<) which is a variable assigned with multi-line indented JSON text in "pretty" format?

Related Questions

Sponsored Content

36 Answered Questions

[SOLVED] What is the correct JSON content type?

53 Answered Questions

[SOLVED] Can comments be used in JSON?

  • 2008-10-28 20:39:03
  • Michael Gundlach
  • 2358563 View
  • 7680 Score
  • 53 Answer
  • Tags:   json comments

55 Answered Questions

[SOLVED] How can I pretty-print JSON in a shell script?

41 Answered Questions

[SOLVED] How do I format a Microsoft JSON date?

34 Answered Questions

[SOLVED] PUT vs. POST in REST

  • 2009-03-10 14:25:20
  • alex
  • 2404575 View
  • 5427 Score
  • 34 Answer
  • Tags:   http rest post put

7 Answered Questions

[SOLVED] Why does Google prepend while(1); to their JSON responses?

24 Answered Questions

[SOLVED] pretty-print JSON using JavaScript

10 Answered Questions

[SOLVED] How to send a header using a HTTP request through a curl call?

  • 2008-12-10 16:38:57
  • gagneet
  • 1714789 View
  • 1466 Score
  • 10 Answer
  • Tags:   curl http-headers

Sponsored Content