# java11新特性
# Http客户端API
# 核心概念
Java 11 新增的 java.net.http.HttpClient 是新一代 HTTP 客户端,核心优势:
- 支持同步 / 异步请求
- 原生支持 HTTP/2 和 WebSocket
- 基于流式 API 设计,简洁易用
- 内置超时、重定向、认证等配置
- 替代第三方库(如 OkHttp、Apache HttpClient)的原生方案
核心类:
HttpClient:创建 HTTP 客户端实例(可配置超时、重定向策略等)HttpRequest:构建 HTTP 请求(URL、方法、头信息、请求体等)HttpResponse:接收 HTTP 响应(状态码、响应体、头信息等)
public class HttpDemo {
public static void main(String[] args) throws IOException, InterruptedException {
// 1. 创建 HttpClient 实例
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofMillis(5000))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
//2. 构建get请求
HttpRequest request = HttpRequest.newBuilder().header("User-Agent", "Java HttpClient")
.uri(URI.create("https://www.baidu.com"))
.GET()
.build();
//3. 构建post请求
HttpRequest request1 = HttpRequest.newBuilder().header("Content-Type", "application/json")
.uri(URI.create("https://www.baidu.com"))
.POST(HttpRequest.BodyPublishers.ofString("hello world"))
.build();
//4. 发送get请求
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("get响应体" + response.body());
System.out.println("get状态码" + response.statusCode());
System.out.println("get响应头" + response.headers());
//5.发送post请求
HttpResponse<String> response1 = httpClient.send(request1, HttpResponse.BodyHandlers.ofString());
System.out.println("post响应体" + response1.body());
System.out.println("post状态码" + response1.statusCode());
System.out.println("post响应头" + response1.headers());
//6.发送异步请求
CompletableFuture<HttpResponse<String>> sendAsync = httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString());
sendAsync.thenApply(HttpResponse::body).thenAccept(System.out::println);
try {
Thread.sleep(5000); // 休眠5秒,给异步任务执行时间
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
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
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
# String类的新方法
1.基本字符串处理和检查
public class StringDemo {
public static void main(String[] args) {
String s="hello world";
String s1=" ";
System.out.println(s.isBlank());//false
System.out.println(s1.isBlank());// true
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
2.strip
trim():仅去除 ASCII 码中 \u0000 到 \u0020 范围内的空白字符(主要是空格 \u0020、制表符 \t、换行 \n 等),不识别 Unicode 全角空格、非断行空格等; strip():基于 Unicode 标准(Character.isWhitespace(int))识别所有空白字符,包括全角空格、非断行空格、中文空格等,覆盖范围更广。
public static void main(String[] args) {
String text=" hello world ";
System.out.println("'"+text.strip()+"'");//'hello world' 去除全部
System.out.println("'"+text.stripLeading()+"'");//'hello world '去除首部
System.out.println("'"+text.stripTrailing()+"'");//' hello world' 去除尾部
}
1
2
3
4
5
6
2
3
4
5
6
3.lines(),处理字符串更加简单
String multiLine = """
这是第一行字符串
这是第二行字符串
这是第三行,包含特殊字符:"双引号"、\\反斜杠、\t制表符
无需手动加\\n换行,文本块会保留换行格式
""";
multiLine.lines().map(line->"处理"+line)
.forEach(System.out::println);
long count = multiLine.lines().count();
System.out.println(count);
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
4.repeat(),重复字符串
System.out.println("hello".repeat(3));
1
# File类新方法
极大的简化了文件读取和写入的方法
public class LegacyFileRead {
public static void main(String[] args) throws Exception {
Path filePath = Paths.get("D:\\code1\\Algorithm\\src\\main\\java\\test\\test.txt"); // 目标文件路径
//1.写文件
Files.writeString(filePath, "hello world");
//2.读取文件为字符串
String contentUtf8 = Files.readString(filePath);
System.out.println("UTF-8 读取内容:\n" + contentUtf8);
//3.传统读法
String content;
try (BufferedReader br = Files.newBufferedReader(filePath)) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
content = sb.toString();
}
System.out.println("传统读取内容:\n" + content);
//4.流式读法
String content2 = Files.lines(filePath).collect(Collectors.joining(System.lineSeparator()));
System.out.println("流式读取内容:\n" + content2);
}
}
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
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