HttpURLConnection
很长一段时间的 HTTP 通信类。但随着时间的推移,应用程序的需求变得复杂和更加苛刻。在 Java 11 之前,开发人员不得不求助于功能丰富的库,如Apache HttpComponents或OkHttp等。HttpClient
实现作为实验性功能。它随着时间的推移不断发展,现在是 Java 11 的最终特性。现在 Java 应用程序可以进行 HTTP 通信,而无需任何外部依赖。
java.net.http
模块的典型 HTTP 交互看起来像-
HttpResponse
.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());
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);
}
});
}
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
要执行上面的类,直接用java
命令运行它。
$ java HelloWorld.java
Hello World!
请注意,该程序不能使用除
java.base module
. 而 program 只能是单文件 program。
n
次数。它返回一个字符串,其值是给定字符串重复 N 次的串联。public class HelloWorld
{
public static void main(String[] args)
{
String str = "1".repeat(5);
System.out.println(str); //11111
}
}
StringUtils.java
.
public class HelloWorld
{
public static void main(String[] args)
{
"1".isBlank(); //false
"".isBlank(); //true
" ".isBlank(); //true
}
}
public class HelloWorld
{
public static void main(String[] args)
{
" hi ".strip(); //"hi"
" hi ".stripLeading(); //"hi "
" hi ".stripTrailing(); //" hi"
}
}
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);
}
}
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
}
}
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);
}
}
true
,否则返回false
。有时,它迫使我们编写不可读的否定条件。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
}
}
https://www.leftso.com/article/865.html