Java 11(于2018年9月发布)包含许多重要且有用的更新。让无涯教程看看它为开发人员和建筑师带来的新函数和改进。
Java长时间使用 HttpURLConnection
类进行HTTP通信。但是随着时间的流逝,要求变得越来越复杂,对应用程序的要求也越来越高。在Java 11之前,开发人员不得不使用函数丰富的库,例如 Apache HttpComponents 或 OkHttp 等。
无涯教程看到了 Java 9 版本,其中包含 HttpClient
实现作为实验性函数。随着时间的流逝,它已经成为Java 11的最终函数。现在,Java应用程序可以进行HTTP通信,而无需任何外部依赖。
java.net.http
模块的典型HTTP交互看起来像-
HttpResponse
中包含的信息。HTTP API可以处理同步和异步通信。
请注意,http客户端API如何使用 builder模式创建复杂对象。
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; HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); try { String urlEndpoint = "https://postman-echo.com/get"; URI uri = URI.create(urlEndpoint + "?foo1=bar1&foo2=bar2"); HttpRequest request = HttpRequest.newBuilder().uri(uri).build(); HttpResponse<String> response = httpClient.send(request,HttpResponse.BodyHandlers.ofString()); } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } System.out.println("Status code: " + response.statusCode()); System.out.println("Headers: " + response.headers().allValues("content-type")); System.out.println("Body: " + response.body());
如果无涯教程不想等待响应,那么异步通信很有用。提供了回调处理程序,可在响应可用时执行。
注意,使用 sendAsync()方法发送异步请求。
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; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; final List<URI> uris = Stream.of( "https://www.google.com/", "https://www.github.com/", "https://www.yahoo.com/" ).map(URI::create).collect(toList()); HttpClient httpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(10)) .followRedirects(HttpClient.Redirect.ALWAYS) .build(); CompletableFuture[] futures = uris.stream().map(uri -> verifyUri(httpClient, uri)).toArray(CompletableFuture[]::new); CompletableFuture.allOf(futures).join(); private CompletableFuture<Void> verifyUri(HttpClient httpClient, URI uri) { HttpRequest request = HttpRequest.newBuilder().timeout(Duration.ofSeconds(5)).uri(uri).build(); return httpClient.sendAsync(request,HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::statusCode) .thenApply(statusCode -> statusCode == 200) .exceptionally(ex -> false) .thenAccept(valid -> { if (valid) { System.out.println("[SUCCESS] Verified " + uri); } else { System.out.println("[FAILURE] Could not " + "verify " + uri); } }); }
传统上,对于无涯教程要执行的每个程序,都需要先对其进行编译。用于测试目的的小型程序似乎不必要地耗时。
Java 11对其进行了更改,现在可以执行单个文件中包含的Java源代码,而无需先对其进行编译。
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }
要执行上述类,请直接使用 java
命令运行它。
$ java HelloWorld.java Hello World!
String.repeat(Integer) - 此方法只是重复字符串 n
次。它返回一个字符串,其值是重复N次给定字符串的串联。
如果此字符串为空或count为零,则返回空字符串。
public class HelloWorld { public static void main(String[] args) { String str = "1".repeat(5); System.out.println(str); //11111 } }
String.isBlank() - 此方法指示字符串是空还是仅包含空格。以前,一直在Apache的 StringUtils.java
中使用它。
public class HelloWorld { public static void main(String[] args) { "1".isBlank(); //false "".isBlank(); //true " ".isBlank(); //true } }
String.strip() - 此方法需要除去前导和尾随空白。通过使用 String.stripLeading()仅删除开头字符,或者通过使用 String.stripTrailing()仅删除结尾字符,甚至可以更具体。
public class HelloWorld { public static void main(String[] args) { " hi ".strip(); //"hi" " hi ".stripLeading(); //"hi " " hi ".stripTrailing(); //" hi" } }
String.lines() - 此方法有助于将多行文本作为 Stream 处理。
public class HelloWorld { public static void main(String[] args) { String testString = "hello\nworld\nis\nexecuted"; List<String> lines = new ArrayList<>(); testString.lines().forEach(line -> lines.add(line)); assertEquals(List.of("hello", "world", "is", "executed"), lines); } }
在Java 11之前,将集合转换为数组并不容易。 Java 11使转换更加方便。
链接:https://www.learnfk.comhttps://www.learnfk.com/java/java11-features-enhancements.html
来源:LearnFk无涯教程网
public class HelloWorld { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("alex"); names.add("brian"); names.add("charles"); String[] namesArr1 = names.toArray(new String[names.size()]);//Before Java 11 String[] namesArr2 = names.toArray(String[]::new); //Since Java 11 } }
使用这些重载方法,Java 11的目的是减少大量样板代码,从而使文件读写更加容易。
public class HelloWorld { public static void main(String[] args) { //Read file as string URI txtFileUri = getClass().getClassLoader().getResource("helloworld.txt").toURI(); String content = Files.readString(Path.of(txtFileUri),Charset.defaultCharset()); //Write string to file Path tmpFilePath = Path.of(File.createTempFile("tempFile", ".tmp").toURI()); Path returnedFilePath = Files.writeString(tmpFilePath,"Hello World!", Charset.defaultCharset(),StandardOpenOption.WRITE); } }
Optional是一个集合对象,可能包含也可能不包含非null值。如果不存在任何值,则该对象被认为是空的。
如果存在值,则以前存在的方法 isPresent()返回 true
,否则返回 false
。
isEmpty()方法与 isPresent()
方法相反,如果存在值,则返回 false
,否则返回 true
。
public class HelloWorld { public static void main(String[] args) { String currentTime = null; assertTrue(!Optional.ofNullable(currentTime).isPresent()); //It's negative condition assertTrue(Optional.ofNullable(currentTime).isEmpty()); //Write it like this currentTime = "12:00 PM"; assertFalse(!Optional.ofNullable(currentTime).isPresent()); //It's negative condition assertFalse(Optional.ofNullable(currentTime).isEmpty()); //Write it like this } }
请问您有关Java 11中这些新API更改的问题。参考: Java 11版本文档
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)