例如,有一个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*
答案 0 :(得分: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));
}