• 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);
    	}
    }
    
    
  • 相关阅读:
    洛谷P3313&BZOJ-3531【SDOI2014】旅行--线段树动态开点+树链剖分
    BZOJ3932【CQOI2015】任务查询系统&洛谷P3168--主席树区间前K小+差分
    博客中的代码CE说明
    栗栗的书架--洛谷P2468【SDOI2010】&BZOJ 1926二分+前缀和+主席树
    hdu1010--Tempter of the Bone(迷宫)
    hdu1242 Rescue DFS(路径探索题)
    hdu 1241--入门DFS
    注意引用的用法
    划分树---hdu4417---区间查找(不)大于h的个数
    程序员能力矩阵
  • 原文地址:https://www.cnblogs.com/androidsuperman/p/10351130.html
Copyright © 2020-2023  润新知