如何使用Jersey Client API在RESTful调用上添加Headers

问题描述 投票:34回答:6

这是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)

我想我没有正确添加标题。

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

谢谢

java rest header request jersey
6个回答
17
投票

我认为你正在寻找标题(名称,值)方法。见WebResource.header(String, Object)

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


35
投票

我使用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 = 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);

16
投票

试试这个!

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你可以添加任意数量的标题!


2
投票

如果你想为所有Jersey响应添加标题,你也可以使用来自ContainerResponseFilterJersey's filter documentation

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

确保使用@Provider注释或通过web.xml的传统方法在项目中正确初始化它。


2
投票
String sBodys="Body";
HashMap<String,String> headers= new HashMap<>();
Client c = Client.create();
WebResource resource = c.resource("http://consulta/rs");
WebResource.Builder builder = resource.accept(MediaType.APPLICATION_JSON);
builder.type(MediaType.APPLICATION_JSON);
if(headers!=null){
      LOGGER.debug("se setean los headers");
      for (Map.Entry<String, String> entry : headers.entrySet()) {
          String key = entry.getKey();
          String value = entry.getValue();
          LOGGER.debug("key: "+entry.getKey());
          LOGGER.debug("value: "+entry.getValue());
          builder.header(key, value);
      }
  }
ClientResponse response = builder.post(ClientResponse.class,sBodys);

1
投票

此代码段工作正常,用于使用Jersey客户端发送承载令牌。

    WebTarget webTarget = client.target("endpoint");

    Invocation.Builder invocationBuilder =  webTarget.request(MediaType.APPLICATION_JSON);
    invocationBuilder.header("Authorization", "Bearer "+"Api Key");

    Response response = invocationBuilder.get();

    String responseData = response.readEntity(String.class);

    System.out.println(response.getStatus());
    System.out.println("responseData "+responseData);
© www.soinside.com 2019 - 2024. All rights reserved.