将下载的文件保存到本地,使用HttpResponse.BodyHandler.asFile(Path):
HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://labs.consol.de/")) .GET() .build(); Path tempFile = Files.createTempFile("consol-labs-home", ".html"); HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandler.asFile(tempFile)); System.out.println(response.statusCode()); System.out.println(response.body());2. 通过POST上传文件
用POST上传本地文件也变得十分简单,使用HttpRequest.BodyProcessor:
HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("http://localhost:8080/upload/")) .POST(HttpRequest.BodyProcessor.fromFile(Paths.get("/tmp/file-to-upload.txt"))) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.discard(null)); System.out.println(response.statusCode());3. 异步HTTP请求
异步HTTP请求也变得简单,由HttpClient#sendAsync() 代替 HttpClient#send 。如果服务端支持,你甚至可以取消执行中的请求:
HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://labs.consol.de/")) .GET() .build(); CompletableFuture<HttpResponse<String>> response = client.sendAsync(request, HttpResponse.BodyHandler.asString()); Thread.sleep(5000); if(response.isDone()) { System.out.println(response.get().statusCode()); System.out.println(response.get().body()); } else { response.cancel(true); System.out.println("Request took more than 5 seconds... cancelling."); }4. 使用系统代理设置
HttpClient client = HttpClient.newBuilder() .proxy(ProxySelector.getDefault()) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://labs.consol.de")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); System.out.println(response.statusCode()); System.out.println(response.body());5.基本认证 Basic Authentication
HttpClient client = HttpClient.newBuilder() .authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password".toCharArray()); } }) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://labs.consol.de")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); System.out.println(response.statusCode()); System.out.println(response.body());结论