Reputation: 143
I have an API documentation. My goal using this doc make a post request to retrieve clients from external api using WebClient. Here the example of the request:
url: "https//:anyurl.com"
{
"command": "getClients"
}
Here how the response looks like:
{
"available": true,
"data": [
{
"id": "1",
"name": "Some description",
"date": "date",
},
{
"id": "2",
"name": "SomeName",
"date": "date",
}
]
}
Here how I did by now:
public class Main {
public static void main(String[] args) throws URISyntaxException {
WebClient client = WebClient.create();
MultiValueMap<String, String> bodyValues = new LinkedMultiValueMap<>();
bodyValues.add("command", "getClients");
WebClient.ResponseSpec response = client.post()
.uri(new URI("https//:anyurl.com"))
.header("token", "myToken") //I have a header as well
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromFormData(bodyValues))
.retrieve();
System.out.println(response);
}
The response class:
public class ClientList {
private Boolean available;
private List<Clients> data;
}
@Document(collection = "clients")
public class Clients {
@Id
private Long id;
private String name;
private Timestamp date;
//getters and setters
}
By now it returns nothing. Is there any solution?
Upvotes: 0
Views: 1399
Reputation: 17510
Can you please try the following? I am guessing that your Mono
was not being subscribed and thus the request was never completed.
public class Main {
public static void main(String[] args) throws URISyntaxException {
WebClient client = WebClient.create();
RequestDto requestBody = RequestDto("getClients");
client.post()
.uri(new URI("https//:anyurl.com"))
.header("token", "myToken") //I have a header as well
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.bodyValue(requestBody)
.retrieve()
.bodyToMono(ClientList.class)
.subscribe(response -> System.out.println(response));
}
}
Assuming you have DTO classes as follows:
public class RequestDto {
private String command;
private RequestDataDto data;
// constructor, getter , setter
}
public class RequestDataDto {
private int start;
private int finish;
// constructor, getter , setter
}
Upvotes: 1
Reputation: 1129
Sending json
is the default way for webclient
, so all you need to do is to pass in the body correctly.
here are the ways:
.body(Mono.just(data))
or:
.body(BodyInserters.fromValue(data))
Upvotes: 0