forked from bage2014/study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClientTest.java
More file actions
55 lines (45 loc) · 1.81 KB
/
Copy pathHttpClientTest.java
File metadata and controls
55 lines (45 loc) · 1.81 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
package com.bage.study.java11;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
/**
* https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html
*
*/
public class HttpClientTest {
public static void main(String[] args) throws Exception {
// basic();
async();
}
private static void basic() throws IOException, InterruptedException {
HttpClient build = HttpClient.newBuilder()
// .proxy() // 代理设置
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://github.com/bage2014/study/tree/master/study-todo"))
.GET()
.build();
HttpResponse<String> send = build.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(send.body());
}
private static void async() throws InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://github.com/bage2014/study/tree/master/study-todo"))
.timeout(Duration.ofMinutes(2))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{}"))
// .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("file.json")))
.build();
HttpClient client = HttpClient.newBuilder()
// .proxy() // 代理设置
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.whenComplete((response,throwable)->{
System.out.println(response.body());
});
Thread.sleep(3000L);
}
}