Java11新特性之HttpClient小试牛刀

时间:2021-05-20


本文主要研究一下Java11的HttpClient的基本使用。

变化

  • 从java9的jdk.incubator.httpclient模块迁移到java.net.http模块,包名由jdk.incubator.http改为java.net.http
  • 原来的诸如HttpResponse.BodyHandler.asString()方法变更为HttpResponse.BodyHandlers.ofString(),变化一为BodyHandler改为BodyHandlers,变化二为asXXX()之类的方法改为ofXXX(),由as改为of
  • 实例

    设置超时时间

    @Test public void testTimeout() throws IOException, InterruptedException { //1.set connect timeout HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofMillis(5000)) .followRedirects(HttpClient.Redirect.NORMAL) .build(); //2.set read timeout HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://openjdk.java.net/")) .timeout(Duration.ofMillis(5009)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); }

    HttpConnectTimeoutException实例

    Caused by: java.net.http.HttpConnectTimeoutException: HTTP connect timed out at java.net.http/jdk.internal.net.http.ResponseTimerEvent.handle(ResponseTimerEvent.java:68) at java.net.http/jdk.internal.net.http.HttpClientImpl.purgeTimeoutsAndReturnNextDeadline(HttpClientImpl.java:1248) at java.net.http/jdk.internal.net.http.HttpClientImpl$SelectorManager.run(HttpClientImpl.java:877)Caused by: java.net.ConnectException: HTTP connect timed out at java.net.http/jdk.internal.net.http.ResponseTimerEvent.handle(ResponseTimerEvent.java:69) ... 2 more

    HttpTimeoutException实例

    java.net.http.HttpTimeoutException: request timed out at java.net.http/jdk.internal.net.http.HttpClientImpl.send(HttpClientImpl.java:559) at java.net.http/jdk.internal.net.http.HttpClientFacade.send(HttpClientFacade.java:119) at com.example.HttpClientTest.testTimeout(HttpClientTest.java:40)

    设置authenticator

    @Test public void testBasicAuth() throws IOException, InterruptedException { HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofMillis(5000)) .authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("admin","password".toCharArray()); } }) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8080/json/info")) .timeout(Duration.ofMillis(5009)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body()); }
  • authenticator可以用来设置HTTP authentication,比如Basic authentication
  • 虽然Basic authentication也可以自己设置header,不过通过authenticator省得自己去构造header
  • 设置header

    @Test public void testCookies() throws IOException, InterruptedException { HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofMillis(5000)) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8080/json/cookie")) .header("Cookie","JSESSIONID=4f994730-32d7-4e22-a18b-25667ddeb636; userId=java11") .timeout(Duration.ofMillis(5009)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body()); }

    通过request可以自己设置header

    GET

    同步

    @Test public void testSyncGet() throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://pletionStage<T> getBody() { return result; } }
  • BodySubscriber接口继承了Flow.Subscriber<List<ByteBuffer>>接口
  • 这里的Subscription来自Flow类,该类是java9引入的,里头包含了支持Reactive Streams的实现
  • 小结

    HttpClient在Java11从incubator变为正式版,相对于传统的HttpUrlConnection其提升可不是一点半点,不仅支持异步,也支持reactive streams,同时也支持了HTTP2以及WebSocket,非常值得大家使用。

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

    声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

    相关文章