如何使用Jersey向正在运行的REST服务发送请求?

问题描述 投票:-1回答:1

例如,有一个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 java-ee jersey-2.0
1个回答
0
投票

例如:

    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));
    }
© www.soinside.com 2019 - 2024. All rights reserved.