Skip to content

Commit 82ffab7

Browse files
committed
Add HTTP, REST & JSON code snippets
1 parent d621d21 commit 82ffab7

14 files changed

+447
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import java.net.URI;
2+
import java.net.URISyntaxException;
3+
import java.net.http.HttpClient;
4+
import java.net.http.HttpRequest;
5+
import java.net.http.HttpResponse.BodyHandlers;
6+
import java.util.concurrent.CompletableFuture;
7+
import java.util.concurrent.ExecutorService;
8+
import java.util.concurrent.Executors;
9+
10+
public class AsyncSongLyricsRetriever {
11+
12+
public static void getLyricsAsync(String artist, String song) {
13+
try (ExecutorService executor = Executors.newCachedThreadPool()) {
14+
HttpClient client =
15+
HttpClient.newBuilder().executor(executor).build(); // configure custom executor or use the default
16+
17+
URI uri = new URI("https", "api.lyrics.ovh", "/v1/" + artist + "/" + song, null);
18+
System.out.println(uri);
19+
20+
HttpRequest request = HttpRequest.newBuilder().uri(uri).build();
21+
System.out.println("Thread calling sendAsync(): " + Thread.currentThread().getName());
22+
23+
CompletableFuture<String> future = client.sendAsync(request, BodyHandlers.ofString())
24+
.thenApply(x -> {
25+
System.out.println("Thread executing thenApply(): " + Thread.currentThread().getName());
26+
return x.body();
27+
});
28+
future.thenAcceptAsync(x -> {
29+
System.out.println("Thread executing thenAccept(): " + Thread.currentThread().getName());
30+
System.out.println(x);
31+
}, executor);
32+
System.out.println("The HTTP call is fired. Performing some other work...");
33+
34+
// wait for the async HTTP call
35+
future.join();
36+
37+
// ExecutorService is AutoCloseable since Java 19, so its shutdown() method will be automatically invoked.
38+
} catch (URISyntaxException e) {
39+
throw new RuntimeException(e);
40+
}
41+
}
42+
43+
public static void main(String... args) throws Exception {
44+
AsyncSongLyricsRetriever.getLyricsAsync("Adele", "Hello");
45+
}
46+
47+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.lang.reflect.Type;
2+
import java.util.List;
3+
import java.util.Map;
4+
5+
import com.google.gson.Gson;
6+
import com.google.gson.reflect.TypeToken;
7+
8+
public class CollectionsMain {
9+
10+
public static void main(String[] args) {
11+
// Lists example
12+
List<Developer> devs = List.of(
13+
new Developer("Kelsey", 28, "Google, Inc"),
14+
new Developer("Wesley", 20, "Google, Inc"));
15+
16+
Gson gson = new Gson();
17+
String json = gson.toJson(devs);
18+
19+
System.out.println(json);
20+
21+
Type type = new TypeToken<List<Developer>>() {
22+
}.getType();
23+
List<Developer> devsAgain = gson.fromJson(json, type);
24+
25+
System.out.println(devsAgain.size()); // 2
26+
27+
// Maps example
28+
json = "{\"apple\":1,\"banana\":2,\"cherry\":3}";
29+
30+
Map<String, Integer> map = gson.fromJson(json, new TypeToken<Map<String, Integer>>() {
31+
}.getType());
32+
33+
System.out.println(map); // {apple=1, banana=2, cherry=3}
34+
}
35+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import com.google.gson.annotations.SerializedName;
2+
3+
public record DevManager(String name, @SerializedName("unit") String department, int level) {
4+
// Gson's @SerializedName annotation is also supported for record components
5+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import com.google.gson.annotations.SerializedName;
2+
3+
public class Developer {
4+
5+
private String name;
6+
private int age;
7+
@SerializedName("employer") // this sets custom name to the serialized field
8+
private transient String company; // remove transient keyword to serialize
9+
10+
public Developer(String name, int age, String company) {
11+
this.name = name;
12+
this.age = age;
13+
this.company = company;
14+
}
15+
16+
public String getName() {
17+
return name;
18+
}
19+
20+
public void setName(String name) {
21+
this.name = name;
22+
}
23+
24+
public int getAge() {
25+
return age;
26+
}
27+
28+
public void setAge(int age) {
29+
this.age = age;
30+
}
31+
32+
public String getCompany() {
33+
return company;
34+
}
35+
36+
public void setCompany(String company) {
37+
this.company = company;
38+
}
39+
40+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import java.net.URI;
2+
import java.net.http.HttpClient;
3+
import java.net.http.HttpRequest;
4+
import java.net.http.HttpResponse;
5+
import java.nio.file.Path;
6+
7+
public class FileDownload {
8+
9+
public static void main(String... args) throws Exception {
10+
var url = "https://www.7-zip.org/a/7z1806-x64.exe";
11+
12+
var client = HttpClient.newBuilder().build();
13+
var request = HttpRequest.newBuilder().uri(URI.create(url)).build();
14+
15+
Path localFile = Path.of("7z.exe");
16+
17+
HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(localFile));
18+
}
19+
20+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import com.google.gson.Gson;
2+
3+
public class FromJsonMain {
4+
5+
public static void main(String[] args) {
6+
String json = "{\"name\": \"Wesley\", \"age\": 20 }";
7+
8+
Gson gson = new Gson();
9+
Developer dev = gson.fromJson(json, Developer.class);
10+
11+
System.out.printf("%s, %d years old, %s%n", dev.getName(), dev.getAge(), dev.getCompany());
12+
}
13+
14+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import com.google.gson.Gson;
2+
3+
import java.io.FileReader;
4+
import java.io.IOException;
5+
import java.util.List;
6+
7+
public class JsonReaderMain {
8+
9+
public static void main(String[] args) throws IOException {
10+
Gson gson = new Gson();
11+
12+
FileReader reader = new FileReader("src/devs.json");
13+
List<Developer> devs = gson.fromJson(reader, List.class);
14+
System.out.println(devs);
15+
}
16+
17+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import java.net.URI;
2+
import java.net.http.HttpClient;
3+
import java.net.http.HttpRequest;
4+
import java.net.http.HttpResponse.BodyHandlers;
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
import java.util.concurrent.CompletableFuture;
8+
import java.util.concurrent.ExecutorService;
9+
import java.util.concurrent.Executors;
10+
11+
public class ParallelHttpRequestsSender {
12+
13+
private static final String WEB_SITE = "http://www.google.com";
14+
private static final int PARALLEL_REQUESTS = 100;
15+
16+
public long executeRequestsSync(HttpClient client, HttpRequest request) throws Exception {
17+
// send some synchronous requests and measure time
18+
long startTime = System.currentTimeMillis();
19+
20+
for (int i = 0; i < PARALLEL_REQUESTS; i++) {
21+
client.send(request, BodyHandlers.ofString()).body();
22+
}
23+
24+
return System.currentTimeMillis() - startTime;
25+
}
26+
27+
public long executeRequestsAsync(HttpClient client, HttpRequest request) {
28+
List<CompletableFuture<String>> futures = new ArrayList<>();
29+
30+
// send some asynchronous requests and measure time
31+
long startTime = System.currentTimeMillis();
32+
33+
for (int i = 0; i < PARALLEL_REQUESTS; i++) {
34+
futures.add(client.sendAsync(request, BodyHandlers.ofString()).thenApply(x -> {
35+
System.out.println("thenApply() thread: " + Thread.currentThread().getName());
36+
return x.body();
37+
}));
38+
}
39+
40+
// uncomment to dump responses to console
41+
// futures.stream().map(f -> f.join()).forEach(System.out::println);
42+
43+
// wait for all futures to complete
44+
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
45+
46+
return System.currentTimeMillis() - startTime;
47+
}
48+
49+
public static void main(String... args) throws Exception {
50+
try (ExecutorService executor = Executors.newCachedThreadPool()) {
51+
HttpClient client =
52+
HttpClient.newBuilder().executor(executor).build(); // configure custom executor or use the default
53+
54+
// build a request
55+
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(WEB_SITE)).build();
56+
57+
var sender = new ParallelHttpRequestsSender();
58+
59+
long syncExecutionTime = sender.executeRequestsSync(client, request);
60+
long asyncExecutionTime = sender.executeRequestsAsync(client, request);
61+
62+
System.out.println("Async: " + asyncExecutionTime + " Sync: " + syncExecutionTime);
63+
64+
// ExecutorService is AutoCloseable since Java 19, so its shutdown() method will be automatically invoked.
65+
}
66+
}
67+
68+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.io.BufferedReader;
2+
import java.io.IOException;
3+
import java.io.InputStreamReader;
4+
import java.io.PrintWriter;
5+
import java.net.Socket;
6+
7+
public class SimpleHttpCaller {
8+
9+
private static final String HOST = "google.com";
10+
private static final int HTTP_PORT = 80;
11+
private static final String HTTP_REQUEST = "GET / HTTP/1.1" + System.lineSeparator();
12+
13+
public static void main(String[] args) {
14+
15+
try (Socket socket = new Socket(HOST, HTTP_PORT);
16+
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); // autoflush on
17+
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
18+
19+
writer.println(HTTP_REQUEST);
20+
21+
String line;
22+
while ((line = reader.readLine()) != null) {
23+
System.out.println(line);
24+
}
25+
26+
} catch (IOException e) {
27+
throw new RuntimeException("Could not access web site", e);
28+
}
29+
30+
}
31+
32+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import java.net.URI;
2+
import java.net.http.HttpClient;
3+
import java.net.http.HttpRequest;
4+
import java.net.http.HttpResponse.BodyHandlers;
5+
6+
public class SyncSongLyricsRetriever {
7+
8+
public String getLyricsSync(String artist, String song) throws Exception {
9+
HttpClient client = HttpClient.newBuilder().build();
10+
11+
URI uri = new URI("https", "api.lyrics.ovh", "/v1/" + artist + "/" + song, null);
12+
System.out.println(uri);
13+
14+
HttpRequest request = HttpRequest.newBuilder().uri(uri).build();
15+
return client.send(request, BodyHandlers.ofString()).body();
16+
}
17+
18+
public static void main(String... args) throws Exception {
19+
System.out.println(new SyncSongLyricsRetriever().getLyricsSync("Adele", "Hello"));
20+
}
21+
22+
}

0 commit comments

Comments
 (0)