-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathExample.java
195 lines (164 loc) · 6.75 KB
/
Example.java
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package io.github.biezhi.java11.http;
import com.google.gson.Gson;
import java.net.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static java.util.stream.Collectors.toList;
/**
* Java 11 的 Http Client 示例
* <p>
* 移除了 HttpResponse.BodyHandler.asString()
* 使用 HttpResponse.BodyHandlers.ofString() 代替功能
*
* @author biezhi
* @date 2018/7/10
*/
public class Example {
// 同步调用 GET
public static void syncGet(String uri) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
// 异步调用 GET
public static void asyncGet(String uri) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.build();
CompletableFuture<HttpResponse<String>> responseCompletableFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
responseCompletableFuture.whenComplete((resp, t) -> {
if (t != null) {
t.printStackTrace();
} else {
System.out.println(resp.body());
System.out.println(resp.statusCode());
}
}).join();
}
// 异步调用 POST
public static void asyncPost() throws Exception {
HttpClient client = HttpClient.newHttpClient();
Gson gson = new Gson();
Foo foo = new Foo();
foo.name = "王爵nice";
foo.url = "https://github.com/biezhi";
String jsonBody = gson.toJson(foo);
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://httpbin.org/post"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.whenComplete((resp, t) -> {
if (t != null) {
t.printStackTrace();
} else {
System.out.println(resp.body());
System.out.println(resp.statusCode());
}
}).join();
}
// 下载文件
public static void downloadFile() throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://labs.consol.de/"))
.GET()
.build();
Path tempFile = Files.createTempFile("consol-labs-home", ".html");
HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(tempFile));
System.out.println(response.statusCode());
System.out.println(response.body());
}
// 上传文件
public static void uploadFile() throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://localhost:8080/upload/"))
.POST(HttpRequest.BodyPublishers.ofFile(Paths.get("/tmp/files-to-upload.txt")))
.build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
System.out.println(response.statusCode());
}
// 设置代理
public static void proxy() throws Exception {
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(new InetSocketAddress("127.0.0.1", 1080)))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://www.google.com"))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
// basic 认证
public static void basicAuth() throws Exception {
HttpClient client = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password".toCharArray());
}
})
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://labs.consol.de"))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
// 访问 HTTP2 网址
public static void http2() throws Exception {
HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.version(HttpClient.Version.HTTP_2)
.build()
.sendAsync(HttpRequest.newBuilder()
.uri(new URI("https://http2.akamai.com/demo"))
.GET()
.build(),
HttpResponse.BodyHandlers.ofString())
.whenComplete((resp, t) -> {
if (t != null) {
t.printStackTrace();
} else {
System.out.println(resp.body());
System.out.println(resp.statusCode());
}
}).join();
}
// 并行请求
public void getURIs(List<URI> uris) {
HttpClient client = HttpClient.newHttpClient();
List<HttpRequest> requests = uris.stream()
.map(HttpRequest::newBuilder)
.map(HttpRequest.Builder::build)
.collect(toList());
CompletableFuture.allOf(requests.stream()
.map(request -> client.sendAsync(request, HttpResponse.BodyHandlers.ofString()))
.toArray(CompletableFuture<?>[]::new))
.join();
}
public static void main(String[] args) throws Exception {
// syncGet("https://biezhi.me");
// asyncGet("https://biezhi.me");
asyncPost();
// http2();
}
}