39

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

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

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

谢谢

4

8 回答 8

40

我使用 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);
于 2013-08-21T13:59:02.577 回答
20

我认为您正在寻找 header(name,value) 方法。看WebResource.header(String, Object)

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

于 2013-08-20T21:44:12.003 回答
18

尝试这个!

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

PS 你可以像这样添加任意数量的标题!

于 2016-03-16T08:12:22.847 回答
5

如果要为所有 Jersey 响应添加标头,还可以使用ContainerResponseFilterJersey过滤器文档中的 , :

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

于 2017-08-02T18:50:29.573 回答
3
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);
于 2019-02-22T03:07:11.817 回答
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);
于 2018-10-16T02:15:32.497 回答
0
ClientResponse response = webResource
                               .queryParams(queryParams) //
                               .header("Content-Type", "application/json") //
                               .header("id", "123") //
                               .get(ClientResponse.class) //
;
于 2020-04-05T15:17:02.317 回答
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);
于 2019-11-13T04:02:53.003 回答