Cómo agregar encabezados en una llamada RESTful usando Jersey Client API


Aquí está el Formato para la llamada RESTful:

HEADERS:
    Content-Type: application/json;charset=UTF-8
    Authorization: Bearer Rc7JE8P7XUgSCPogjhdsVLMfITqQQrjg

REQUEST:
    GET https://api.example.com/1/realTime?json={"selection":{"includeAlerts":"true","selectionType":"registered","selectionMatch":"","isTheEvent":"true","includeRuntime":"true"}}

Aquí están mis códigos:

                try
                {
                 Client client = Client.create();
                 WebResource webResource = 
                         client.resource("https://api.example.com/1/realTime?json=
                         {"selection":{"includeAlerts":"true","selectionType":"registered","selectionMatch":"","isTheEvent":"true","includeRuntime":"true"}}");

                 //add header:Content-Type: application/json;charset=UTF-8
                 webResource.setProperty("Content-Type", "application/json;charset=UTF-8");

                 //add header: Authorization Bearer Rc7JE8P7XUgSCPogsdfdLMfITqQQrjg
                 value = "Bearer " + value;
                 webResource.setProperty("Authorization", value);

                 MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
                 queryParams.add("json", js);

                 //Get response from RESTful Server
                 jsonStr = webResource.get(String.class);
                 System.out.println("Testing:");
                 System.out.println(jsonStr);

                }
                catch (Exception e)
                {
                  System.out.println (e.getMessage());
                  e.printStackTrace();
                  System.exit(0);
                }

Pero devuelve error

com.sun.jersey.api.client.UniformInterfaceException: GET https://api.example.com/1/realTime? returned a response status of 500
    at com.sun.jersey.api.client.WebResource.handle(WebResource.java:607)
    at com.sun.jersey.api.client.WebResource.get(WebResource.java:187)
    at net.yorkland.restful.GetThermostatlist.GetThermostats(GetThermostatlist.java:60)

Creo que no agregué encabezados correctamente.

¿Puede alguien ayudarme a arreglarlo? Por favor, dame consejos sobre cómo agregar encabezados a petición.

Gracias

Author: Eric, 2013-08-20

4 answers

Creo que estás buscando el método header(nombre,valor). Ver WebResource.header(String, Object)

Tenga en cuenta que devuelve un constructor, por lo que necesita guardar la salida en su var de WebResource.

 16
Author: TheArchitect,
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-09 16:40:21

Utilizo el método header (name, value) y doy el retorno a WebResource var:

Client client = Client.create();
WebResource webResource =client.resource("uri");

MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("json", js); //set parametes for request

appKey = "Bearer " + appKey; // appKey is unique number

//Get response from RESTful Server get(ClientResponse.class);
ClientResponse response = null;
response = webResource.queryParams(queryParams)
                        .header("Content-Type", "application/json;charset=UTF-8")
    .header("Authorization", appKey)
    .get(ClientResponse.class);

String jsonStr = response.getEntity(String.class);
 35
Author: Eric,
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-02-22 22:01:15

¡Prueba esto!

Client client = ClientBuilder.newClient();

String jsonStr = client
            .target("http:....")
            .request(MediaType.APPLICATION_JSON)

            .header("WM_SVC.NAME", "RegistryService")
            .header("WM_QOS.CORRELATION_ID", "d1f0c0d2-2cf4-497b-b630-06d609d987b0")

            .get(String.class);

P. S Usted puede agregar cualquier número de encabezados como este!

 15
Author: Sanchit Singhania,
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-03-16 08:12:22

Si desea agregar un encabezado a todas las respuestas de Jersey, también puede usar un ContainerResponseFilter, de La documentación del filtro de Jersey :

import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;

@Provider
public class PoweredByResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {

            responseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
    }
}

Asegúrese de inicializarlo correctamente en su proyecto usando la anotación @Provider o a través de formas tradicionales con web.xml.

 2
Author: Shawn S.,
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-08-02 18:50:29