forked from thombergs/code-examples
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathWebClientApp.java
More file actions
74 lines (61 loc) · 1.71 KB
/
Copy pathWebClientApp.java
File metadata and controls
74 lines (61 loc) · 1.71 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
*
*/
package io.pratik;
import java.io.IOException;
import java.util.HashMap;
import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.core5.http.ParseException;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author pratikdas
*
*/
public class WebClientApp {
public void invoke() {
WebClient client = WebClient.create();
client
.get()
.uri(URLConstants.URL)
.header(URLConstants.API_KEY_NAME, URLConstants.API_KEY_VALUE)
.retrieve()
.bodyToMono(String.class)
.subscribe(result->System.out.println(result));
}
public void invokePost() {
WebClient client = WebClient.create();
String result = client
.post()
.uri("https://reqbin.com/echo/post/json")
.body(BodyInserters.fromValue(prepareRequest()))
.exchange()
.flatMap(response -> response.bodyToMono(String.class))
.block();
System.out.println("result::"+result);
}
private String prepareRequest() {
var values = new HashMap<String, String>() {
{
put("Id", "12345");
put("Customer", "Roger Moose");
put("Quantity", "3");
put("Price","167.35");
}
};
var objectMapper = new ObjectMapper();
String requestBody;
try {
requestBody = objectMapper.writeValueAsString(values);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
return requestBody;
}
public static void main(String[] args) throws ClientProtocolException, IOException, ParseException {
new WebClientApp().invoke();
}
}