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

时间:2013-08-20 18:29:46

标签: java rest header request jersey

以下是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)

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

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

谢谢

8 个答案:

答案 0 :(得分: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);

答案 1 :(得分:17)

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

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

答案 2 :(得分: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你可以像这样添加任意数量的标题!

答案 3 :(得分:2)

如果您想为所有泽西岛的回复添加标题,您还可以使用Jersey's filter documentation中的ContainerResponseFilter

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的传统方式在项目中正确初始化它。

答案 4 :(得分:1)

String sBodys =“ Body”;

HashMap标头=新的HashMap <>();

Client c = Client.create();

WebResource资源= 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响应= builder.post(ClientResponse.class,sBodys);

答案 5 :(得分:0)

此代码段适用于使用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);

答案 6 :(得分:0)

这是我的示例。

import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Map;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("key1", "value1");
formData.add("key1", "value2");
WebTarget webTarget = ClientBuilder.newClient().target("https://some.server.url/");
String response = webTarget.path("subpath/subpath2").request().post(Entity.form(formData), String.class);
Map<String, String> gsonResponse = gson.fromJson(response, type);

答案 7 :(得分:0)

ClientResponse response = webResource
                               .queryParams(queryParams) //
                               .header("Content-Type", "application/json") //
                               .header("id", "123") //
                               .get(ClientResponse.class) //
;