forked from thombergs/code-examples
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathHttpClientApp.java
More file actions
82 lines (67 loc) · 2.18 KB
/
Copy pathHttpClientApp.java
File metadata and controls
82 lines (67 loc) · 2.18 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
75
76
77
78
79
80
81
82
/**
*
*/
package io.pratik;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.HashMap;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author pratikdas
*
*/
public class HttpClientApp {
public void invoke() throws URISyntaxException {
HttpClient client = HttpClient.newBuilder().version(Version.HTTP_2).followRedirects(Redirect.NORMAL).build();
HttpRequest request = HttpRequest.newBuilder().uri(new URI(URLConstants.URL)).GET()
.header(URLConstants.API_KEY_NAME, URLConstants.API_KEY_VALUE).timeout(Duration.ofSeconds(10)).build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
public void invokePost() {
try {
String requestBody = prepareRequest();
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://reqbin.com/echo/post/json"))
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.header("Accept", "application/json")
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @return
* @throws JsonProcessingException
*/
private String prepareRequest() throws JsonProcessingException {
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 = objectMapper.writeValueAsString(values);
return requestBody;
}
public static void main(String[] args) throws URISyntaxException {
new HttpClientApp().invoke();
}
}