java 11 标准Java异步HTTP客户端

这是 Java 9 开始引入的一个处理 HTTP 请求的的 HTTP Client API,该 API 支持同步和异步,而在 Java 11 中已经为正式可用状态,你可以在 java.net 包中找到这个 API。

来看一下 HTTP Client 的用法:

var request = HttpRequest.newBuilder()

.uri(URI.create("https://javastack.cn"))

.GET()

.build();

var client = HttpClient.newHttpClient();

// 同步

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

System.out.println(response.body());

// 异步

client.sendAsync(request, HttpResponse.BodyHandlers.ofString())

.thenApply(HttpResponse::body)

.thenAccept(System.out::println);

上面的 .GET() 可以省略,默认请求方式为 Get!

例子:

import static org.junit.Assert.*;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.concurrent.CompletableFuture;

import org.junit.Test;

public class HTTPClientTest {
	
	@Test
	public void testName2() throws Exception {
		HttpClient client = HttpClient.newHttpClient();
		HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:8080/test/")).build();
		BodyHandler<String> responseBodyHandler = BodyHandlers.ofString();
		CompletableFuture<HttpResponse<String>> sendAsync = client.sendAsync(request, responseBodyHandler);
		sendAsync.thenApply(t -> t.body()).thenAccept(System.out::println);
		//HttpResponse<String> response = sendAsync.get();
		//String body = response.body();
		//System.out.println(body);
		
	}
	
	@Test
	public void testName() throws Exception {
		HttpClient client = HttpClient.newHttpClient();
		HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:8080/test/")).build();
		BodyHandler<String> responseBodyHandler = BodyHandlers.ofString();
		HttpResponse<String> response = client.send(request, responseBodyHandler);
		String body = response.body();
		System.out.println(body);
	}
}

posted @ 2019-02-03 22:07  西北野狼  阅读(1942)  评论(0编辑  收藏  举报