【问题标题】:How to send a request to a running REST service using Jersey?如何使用 Jersey 向正在运行的 REST 服务发送请求?
【发布时间】:2019-12-06 09:01:20
【问题描述】:

比如有个REST资源:

 @POST    
 @Path("/test")    
 @Consumes(MediaType.APPLICATION_JSON)
 public Response create(String content){

      ...
 }

如何使用 Jersey 库在客户端中请求此资源?请求示例:

POST http://localhost:8080/test
Authorization: Basic eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjIsInJvbGUiOiJDVVNUT01FUiIsImlzcyI6ImFwcDRwcm8ucnUifQ.rPfB4I-VdJ09ca5ogD5D6c1aYUtySAYAgjW8_TefZSY
Content-Type: application/json

*json content*

【问题讨论】:

标签: rest jakarta-ee jersey-2.0


【解决方案1】:

例如:

    public static void testRequest(){
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target("http://localhost:8080").path("test");

        MyEntity myEntity = ... // создание кастомной сущности
        Entity<MyEntity> entity = Entity.entity(myEntity, MediaType.APPLICATION_JSON);

        Invocation.Builder ib = target.request(MediaType.APPLICATION_JSON_TYPE);
        ib.header("Authorization", "Basic eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjIsInJvbGUiOiJDVVNUT01FUiIsImlzcyI6ImFwcDRwcm8ucnUifQ.rPfB4I-VdJ09ca5ogD5D6c1aYUtySAYAgjW8_TefZSY")
                .header("Content-Type", "application/json");

        String response = ib.post(entity, String.class);            
        System.out.println(response);
    }

否则:

    public static void testRequest(){
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target("http://localhost:8080").path("test");        

        Entity<String> entity = Entity.entity("*SomeString*", MediaType.APPLICATION_JSON);

        Invocation.Builder ib = target.request(MediaType.APPLICATION_JSON_TYPE);
        ib.header("Authorization", "Basic eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjIsInJvbGUiOiJDVVNUT01FUiIsImlzcyI6ImFwcDRwcm8ucnUifQ.rPfB4I-VdJ09ca5ogD5D6c1aYUtySAYAgjW8_TefZSY")
                .header("Content-Type", "application/json");

        Response response = ib.post(entity);            
        System.out.println(response.readEntity(String.class));
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2018-04-14
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    相关资源
    最近更新 更多