Cómo PUBLICAR datos JSON con Curl desde Terminal / Línea de comandos para probar Spring REST?


Uso Ubuntu e instalé Curl en él. Quiero probar mi aplicación Spring REST con Curl. Escribí mi código postal en Java side. Sin embargo, quiero probarlo con Curl. Estoy tratando de publicar datos JSON. Un ejemplo de datos es como este:

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

Utilizo este comando:

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

Devuelve este 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

La descripción del error es la siguiente:

El servidor rechazó esta solicitud porque la entidad de solicitud está en un formato no soportado por la recurso para el método solicitado ().

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

¿Alguna idea sobre el formato correcto del comando Curl?

EDITAR:

Este es mi código PUT lado Java (he probado GET y DELETE y funcionan)

@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;
} 
Author: Navid Vafaei, 2011-08-24

20 answers

Debe establecer su content-type en application/json. Pero -d envía el Content-Type application/x-www-form-urlencoded, que no es aceptado por el lado de Spring.

Mirando la página de manual de curl , creo que puede usar -H:

-H "Content-Type: application/json"

Ejemplo completo:

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

(-H es la abreviatura de --header, -d para --data)

Tenga en cuenta que -request POSTes opcional si utiliza -d, ya que la bandera -d implica una solicitud POST.


En Windows, las cosas son ligeramente diferentes. Ver el hilo de comentarios.

 3378
Author: Sean Patrick Floyd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-03 21:43:03

Intente poner sus datos en un archivo, diga body.json y luego use

curl -H "Content-Type: application/json" --data @body.json http://localhost:8080/ui/webapp/conf
 443
Author: Typisch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-24 10:04:24

Puede que resty te resulte útil: https://github.com/micha/resty

Es un wrapper round CURL que simplifica las peticiones REST de la línea de comandos. Lo apuntas al punto final de la API y te da los comandos PUT y POST. (Ejemplos adaptados de la página de inicio)

$ 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

Además, a menudo es necesario agregar los encabezados de Tipo de contenido. Puede hacer esto una vez, sin embargo, para establecer un valor predeterminado, de agregar archivos de configuración por método por sitio: Establecer opciones de RESTY predeterminadas

 89
Author: mo-seph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-08 14:34:39

Funcionó para mí usando:

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

Fue felizmente mapeado al controlador de resorte:

@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 es un simple POJO con una propiedad id.

 70
Author: Luis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-27 21:47:50

Para Windows, tener una comilla simple para el valor -d no funcionó para mí, pero funcionó después de cambiar a comilla doble. También necesitaba escapar de las comillas dobles dentro de los corchetes rizados.

Es decir, lo siguiente no funcionó:

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

Pero lo siguiente funcionó:

curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path
 59
Author: venkatnz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-27 21:51:04

Como ejemplo, cree un archivo JSON, params.json, y añadir este contenido a la misma:

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

Luego ejecuta este comando:

curl -v -H "Content-Type: application/json" -X POST --data @params.json -u your_username:your_password http://localhost:8000/env/add_server
 39
Author: Eduardo Cerqueira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-22 16:05:09

Esto funcionó bien para mí.

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

Donde

-X Significa el verbo http.

--data Significa los datos que desea enviar.

 33
Author: felipealves.gnu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-01 14:31:40

Me encuentro con el mismo problema. Podría resolverlo especificando

-H "Content-Type: application/json; charset=UTF-8"
 28
Author: Steffen Roller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-15 15:45:09

Usando Ventanas CURL, prueba esto:

curl -X POST -H "Content-Type:application/json" -d "{\"firstName\": \"blablabla\",\"lastName\": \"dummy\",\"id\": \"123456\"}" http-host/_ah/api/employeeendpoint/v1/employee
 24
Author: Márcio Brener,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-12 11:37:54

Si está probando una gran cantidad de JSON send/responses contra una interfaz RESTful, es posible que desee revisar el Postman plug-in para Chrome (que le permite definir manualmente las pruebas de servicio web) y su nodo.compañero de línea de comandos basado en js Newman (que le permite automatizar pruebas contra "colecciones" de pruebas de Postman.) Tanto libre como abierto!

 16
Author: ftexperts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-14 21:40:23

Puede usar Postman con su interfaz gráfica de usuario intuitiva para ensamblar su comando cURL.

  1. Instalar e iniciar Postman
  2. Escriba su URL, Cuerpo de la publicación, Encabezados de solicitud, etc. pp.
  3. Haga clic en Code
  4. Seleccione cURL de la lista desplegable
  5. copie y pegue su comando cURL

Nota: Hay varias opciones para la generación automática de solicitudes en la lista desplegable, por lo que pensé que mi publicación era necesaria en el primer lugar.

 15
Author: kiltek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-25 12:47:20

Esto funcionó bien para mí, además usando autenticación BÁSICA:

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

Por supuesto, nunca debe usar la autenticación BÁSICA sin SSL y un certificado verificado.

Me encontré con esto de nuevo hoy, usando Cygwin cURL 7.49.1 para Windows... Y al usar --data o --data-binary con un argumento JSON, cURL se confundió e interpretaría el {} en el JSON como una plantilla URL. Agregar un argumento -g para desactivar el globbing de cURL solucionó eso.

Véase también Passing una URL con corchetes para curvar.

 13
Author: davenpcj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-27 21:49:25

Esto funcionó para mí:

curl -H "Content-Type: application/json" -X POST -d @./my_json_body.txt http://192.168.1.1/json
 12
Author: Amit Vujic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-16 16:39:51

Un poco tarde para la fiesta, pero no veo esto publicado, así que aquí va, también puedes poner tu json en un archivo y pasarlo a curl usando la opción file file-upload a través de la entrada estándar, así:

 echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -
 11
Author: iloveretards,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-13 19:41:11

HTTPie es una alternativa recomendada a curl porque puede hacer solo

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

Habla JSON de forma predeterminada y se encargará tanto de configurar el encabezado necesario para usted como de codificar datos como JSON válido. También hay:

Some-Header:value

Para los encabezados, y

name==value

Para parámetros de cadena de consulta. Si tiene una gran cantidad de datos, también puede leerlos desde un archivo para que estén codificados en JSON:

 [email protected]
 10
Author: tosh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-23 14:13:44

Estoy usando el siguiente formato para probar con un servidor web.

use -F 'json data'

Asumamos este formato de dict JSON:

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

Ejemplo completo

curl -XPOST your_address/api -F comment='{"who":"some_one", "desc":"get it"}'
 7
Author: user3180641,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-27 21:50:02

Para datos json

curl -H "Content-Type: application/json" -X POST -d '{"params1":"value1","param2":"value2"}' http://localhost:8080/api

Si desea publicar algún archivo

curl -X POST -F "data=@/Users/vishvajitpathak/Desktop/screen_1.png" http://localhost:8080/upload --insecure

En caso de que no quieras meter la pata con https y http:

O Simplemente,

curl -X POST -F "data=@/Users/vishvajitpathak/Desktop/screen_1.png" http://localhost:8080/upload

 6
Author: Vishvajit Pathak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-11 06:52:48

Uso JSON en mi aplicación y es simple como:

curl -X POST -H "Content-Type:application/json" -d '{"params1":"value1","params2":"value2"} hostname:port/api

Pero si tiene un gran número de parámetros, siempre prefiera usar un archivo con el cuerpo de la solicitud JSON como se muestra a continuación:

curl -X POST -H "Content-Type:application/json" -F "data=@/users/suchi/dekstop/JSON_request.txt" hostname:port/api
 4
Author: Suchi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-08 03:15:55

Crear archivo JSON "MyData.json " y añadir contenido:

[
    {
        "Key_one": "Value_one",
        "Key_two": "Value_two",
        "Key_three": "Value_three"
    }
]

Después de esto, necesita ejecutar el siguiente comando:

curl -v -H "Content-Type: application/json" -X POST --data @MyData.json -u USERNAME:PASSWORD http://localhost:8000/env/add_server
 0
Author: Shrish Shrivastava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-08 12:25:04

Puede pasar la extensión del formato que desee como el final de la url. como http://localhost:8080/xx/xxx/xxxx.json

O

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

Nota: debe agregar las dependencias de jackson y jaxb maven en su pom.

 -1
Author: Saurabh Oza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-16 09:57:33