如何使用泽西客户端 API 在 RESTful 调用上添加标头

2022-09-01 03:34:36

以下是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"}}

这是我的代码:

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

但它返回错误

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)

我认为我没有正确添加标题。

有人可以帮我修复它吗?请给我建议如何根据要求添加标题。

谢谢


答案 1

我使用 header(name, value) 方法,并将返回给 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 = webResource.queryParams(queryParams)
    .header("Content-Type", "application/json;charset=UTF-8")
    .header("Authorization", appKey)
    .get(ClientResponse.class);

String jsonStr = response.getEntity(String.class);

答案 2

我想你正在寻找标题(名称,值)方法。请参阅 WebResource.header(String, Object)

请注意,它返回一个生成器,因此您需要将输出保存在webResource var中。