Uso del cliente Jersey para realizar una operación POST


En un método Java, me gustaría usar un objeto cliente Jersey para hacer una operación POST en un servicio web RESTful (también escrito usando Jersey) pero no estoy seguro de cómo usar el cliente para enviar los valores que se utilizarán como FormParam en el servidor. Soy capaz de enviar parámetros de consulta muy bien.

Author: Zoe, 2010-01-26

6 answers

No he hecho esto todavía, pero un poco rápido de Google-Fu revela un consejo técnico sobre blogs.oracle.com con ejemplos de exactamente lo que usted pide.

Ejemplo tomado de la entrada del blog:

MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource
    .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
    .post(ClientResponse.class, formData);

Que cualquier ayuda?

 76
Author: brabster,
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-04-05 18:44:42

A partir de Jersey 2.x, la clase MultivaluedMapImpl se sustituye por MultivaluedHashMap. Puede usarlo para agregar datos de formulario y enviarlos al servidor:

    WebTarget webTarget = client.target("http://www.example.com/some/resource");
    MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
    formData.add("key1", "value1");
    formData.add("key2", "value2");
    Response response = webTarget.request().post(Entity.form(formData));

Tenga en cuenta que la entidad form se envía en el formato de "application/x-www-form-urlencoded".

 41
Author: tonga,
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
2014-08-07 01:43:48

Ahora es el primer ejemplo en la documentación del cliente de Jersey

Ejemplo 5.1. POST request with form parameters

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");

Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");

MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
    .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
        MyJAXBBean.class);
 13
Author: otonglet,
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-18 07:01:09

Si necesita cargar un archivo, deberá usar MediaType.MULTIPART_FORM_DATA_TYPE. Parece que MultivaluedMap no se puede utilizar con eso, así que aquí hay una solución con FormDataMultiPart.

InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload);

FormDataMultiPart part = new FormDataMultiPart();
part.field("String_key", "String_value");
part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE);
String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);
 4
Author: dimuthu,
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
2014-06-05 06:34:40

Más simple:

Form form = new Form();
form.add("id", "1");    
form.add("name", "supercobra");
ClientResponse response = webResource
  .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
  .post(ClientResponse.class, form);
 2
Author: supercobra,
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
2014-11-13 22:46:33

También puedes probar esto:

MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
webResource.path("yourJerseysPathPost").queryParams(formData).post();
 2
Author: RVelarde,
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-04-15 20:21:52