0

I am trying to send an object to the endpoint but I do not understand why I can't do it with .get(), why .post() has to be used? What if the endpoint method takes an object and does something with it and returns an object? I may want to send an object to the endpoint which takes the object as an argument. Is there a way to do it? How to pass a customer object to getCustomer() endpoint.

WebClient.create("http://localhost:8080")
            .get()//why this can not be used? why post has to be used?
            .uri("client/getCustomer")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(customer)//with .get() body cannot be passed.
            .retrieve()
            .bodyToMono(Customer.class);


        @GET
        @Path("/getCustomer")
        @Produces(MediaType.APPLICATION_JSON)
        @Consumes(MediaType.APPLICATION_JSON)
        public Customer getCustomer(Customer customer) {
            //do something
            return customer;
        }
Lisa
  • 129
  • 1
  • 1
  • 8

1 Answers1

1

Edited

In GET methods, the data is sent in the URL. just like: http://www.test.com/users/1

In POST methods, The data is stored in the request body of the HTTP request.

Therefore we should not expect .get() method to have .bodyValue().

Now if you wanna send data using GET method, you should send them in the URL, like below snippet

   WebClient.create("http://localhost:8080")
            .get()
            .uri("client/getCustomer/{customerName}" , "testName")
            .retrieve()
            .bodyToMono(Customer.class);

Useful Spring webClient sample:

spring 5 WebClient and WebTestClient Tutorial with Examples

Further information about POST and GET

HTTP Request Methods

  • I mean why I cannot use .get() and .bodyValue(customer) together? why .post() has to be used in order to send an object to end point as requestbody? – Lisa Jan 12 '20 at 05:43
  • 1
    there is no rule about it. You can send (or omit) the body with **any** http method. – Ritesh Jan 12 '20 at 12:43
  • 1
    @Ritesh you can send data with both of them but in different ways. The GET requests cannot have a message body. But you still can send data to the server using the URL parameters – Mehrdad HosseinNejad Yami Jan 12 '20 at 13:02
  • 1
    There is no such rule that says "The GET requests cannot have a message body". You can send it if you want to. See https://stackoverflow.com/questions/978061. – Ritesh Jan 12 '20 at 13:04