1. Invocation
Invocation is a class that let you create request and execute it by means of its
invoke method. Here is an example of creating an invocation and executing it with some parameters. Note method
buildGet():
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| package org.ximodante.jaxrs.client;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
public class MyInvocation {
//01. Invocation generation with parameter year
public static Invocation prepareRequest(int year) {
//01.1 Create a client
Client client=ClientBuilder.newClient();
return client
// 01.2 Define the URL target
.target("http://localhost:8080/Jaxrs02/firstapi/")
//01.3 Define path
.path("messages")
//01.4 Define query param
.queryParam("year",year)
//01.5 Define media type
.request(MediaType.APPLICATION_JSON)
//01.6 Build a guet invocation
.buildGet();
}
public static void main(String[] args) {
//02. Get the defined invocation with the query param
Invocation inv=prepareRequest(2018);
//03. Get the response
Response resp = inv.invoke();
System.out.println(resp.getStatus());
}
}
|
2. Generics
Jacks provides an akin wrapper class called GenericType<SomeClass>. It can be used in the "GET" of a Request to tell the type of the class. Here is a simple example to wrap a List<MyMessage> class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
public class RestAPIClientGnrc {
public static void main(String[] args) {
//01. Create a client
Client client=ClientBuilder.newClient();
List<?> reponse= client
// 02. Define the URL target
.target("http://localhost:8080/Jaxrs02/firstapi/")
//03. Define path
.path("messages")
//04. Define query param
.queryParam("year",2018)
//05. Define media type
.request(MediaType.APPLICATION_JSON)
//06. Get with the Generic Wrapper
.get(new GenericType<List<MyMessage>>() { });
//07. Outputs the message
System.out.println(reponse);
}
}
|
Notice the "{ }" in the line 24
Comentarios
Publicar un comentario