A tutorial of using JAX-RS client WebClient

Keywords: Programming xml Apache

JAX-RS client programming – >
There are two ways:
① Using the http client tool, we need to customize and parse the HTTP protocol
② This article focuses on the use of WebClient tool class (Brought by CXF) to explain RS client programming.
Using RS WebClient requires importing coordinates in pom.xml file

<!-- Use CXF RS Development -->
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    <version>3.0.1</version>
</dependency>

Create a test class: directly use the
The create method establishes a connection to the calling server resource path.

//create-->Establish connection with calling service resource path
Collection<? extends User> collection = WebClient.create("http://localhost:9997/userService/user")

type data format sent to the server – > corresponding @ consumption
accept the data format passed by the receiving server – > corresponding to @ products
The accept and type methods are one-to-one corresponding to the @ Produces and @ Consumes annotations.

Collection<? extends User> collection = WebClient.create("http://localhost:9997/userService/user")
.accept(MediaType.APPLICATION_XML).getCollection(User.class);
    System.out.println(collection);

getCollection(User.class) means to query all User information. If a User is queried separately, get(User.class) is used;
Full code:

public class RS_Client {
    public static void main(String[] args) {
        //Create -- > establishes a connection with the calling service resource path
        //Data format sent to the server by type -- > @ consumption
        //Accept -- > data format transmitted by receiving server
        //Which way to access the server using Http protocol
        Collection<? extends User> collection = WebClient.create("http://localhost:9997/userService/user").accept(MediaType.APPLICATION_XML).getCollection(User.class);
        System.out.println(collection);
        //Query a user
        User resultUser = WebClient.create("http://localhost:9997/userService/user/1").accept(MediaType.APPLICATION_JSON).get(User.class);
        System.out.println(resultUser);
    }
}

Add with post method:

//Add user
User user = new User();
WebClient.create("http://localhost:9997/userService/user").type(MediaType.APPLICATION_JSON).post(user);

get for query;
put for modification;
Add post;
Delete with delete

Posted by vineld on Sun, 03 May 2020 21:16:32 -0700