使用java11的HttpClient发送网络请求
@Test
public void test1() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://www.baidu.com")).build();
HttpResponse.BodyHandler<String> responseBodyHandler = HttpResponse.BodyHandlers.ofString();
HttpResponse<String> response = client.send(request, responseBodyHandler);
String body = response.body();
System.out.println(body);
HttpResponse.BodyHandler<InputStream> inputStreamBodyHandler = HttpResponse.BodyHandlers.ofInputStream();
HttpResponse<InputStream> httpResponse = client.send(request, inputStreamBodyHandler);
InputStream inputStream = httpResponse.body();
FileOutputStream fis = new FileOutputStream("src/com/hehui/day1214/index.html");
inputStream.transferTo(fis);
}