Hoe POST ik JSON data met Curl vanaf een terminal/commandline naar Test Spring REST?

Ik gebruik Ubuntu en installeerde cURL op het. Ik wil mijn Spring REST applicatie testen met cURL. Ik schreef mijn POST code aan de Java kant. Echter, ik wil het testen met cURL. Ik probeer een JSON data te posten. Voorbeeld data is als volgt:

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

Ik gebruik dit commando:

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

Het geeft deze foutmelding:

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

De foutbeschrijving is deze:

De server weigerde dit verzoek omdat de verzoekentiteit een formaat heeft dat niet wordt ondersteund door de aangevraagde bron voor de aangevraagde methode ().

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

Wat is het juiste formaat van het cURL commando?

Dit is mijn Java-kant PUT code (ik heb getest GET en DELETE en ze werken):

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

Je moet je content-type instellen op application/json. Maar -d stuurt het Content-Type application/x-www-form-urlencoded, wat niet geaccepteerd wordt aan Spring's kant.

Kijkend naar de curl man page, denk ik dat je -H kunt gebruiken:

-H "Content-Type: application/json"

Volledig voorbeeld:

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

(-H is een afkorting voor --header, -d voor --data)

Merk op dat -request POST optioneel is als je -d gebruikt, omdat de -d vlag een POST verzoek impliceert.


Op Windows liggen de zaken iets anders. Zie de commentaar thread.

Commentaren (26)

Probeer je gegevens in een bestand te zetten, zeg body.json en gebruik dan

curl -H "Content-Type: application/json" --data @body.json http://localhost:8080/ui/webapp/conf
Commentaren (10)

Ik loop net tegen hetzelfde probleem aan. Ik kon het oplossen door te specificeren

-H "Content-Type: application/json; charset=UTF-8"
Commentaren (0)