Google

Package java.net.http

In general, asynchronous tasks execute in either the thread invoking the operation, e.g. sending an HTTP request, or by the threads supplied by the client’s executor . Dependent tasks, those that are triggered by returned CompletionStages or CompletableFutures, that do not explicitly specify an executor, execute in the same default executor as that of CompletableFuture , or the invoking thread if the operation completes before the dependent task is registered.

CompletableFuture s returned by this API will throw UnsupportedOperationException for their obtrudeValue and obtrudeException methods. Invoking the cancel method on a CompletableFuture returned by this API may not interrupt the underlying operation, but may be useful to complete, exceptionally, dependent stages that have not already completed.

Unless otherwise stated, null parameter values will cause methods of all classes in this package to throw NullPointerException .

Thrown when a connection, over which an HttpRequest is intended to be sent, is not successfully established within a specified time period.

A BodyPublisher converts high-level Java objects into a flow of byte buffers suitable for sending as a request body.

Implementations of BodyPublisher that implement various useful publishers, such as publishing the request body from a String, or from a file.

Implementations of BodyHandler that implement various useful handlers, such as handling the response body as a String, or streaming the response body to a file.

Implementations of BodySubscriber that implement various useful subscribers, such as converting the response body bytes into a String, or streaming the bytes to a file.

Читайте также:  Java setting string values

Initial response information supplied to a BodyHandler when a response is initially received and before the body is processed.

Источник

Package java.net

The java.net package can be roughly divided in two sections:

  • A Low Level API, which deals with the following abstractions:
    • Addresses, which are networking identifiers, like IP addresses.
    • Sockets, which are basic bidirectional data communication mechanisms.
    • Interfaces, which describe network interfaces.
    • URIs, which represent Universal Resource Identifiers.
    • URLs, which represent Universal Resource Locators.
    • Connections, which represents connections to the resource pointed to by URLs.

    Addresses

    Addresses are used throughout the java.net APIs as either host identifiers, or socket endpoint identifiers.

    But, in most cases, there is no need to deal directly with the subclasses, as the InetAddress abstraction should cover most of the needed functionality.

    About IPv6

    Not all systems have support for the IPv6 protocol, and while the Java networking stack will attempt to detect it and use it transparently when available, it is also possible to disable its use with a system property. In the case where IPv6 is not available, or explicitly disabled, Inet6Address are not valid arguments for most networking operations any more. While methods like InetAddress.getByName(java.lang.String) are guaranteed not to return an Inet6Address when looking up host names, it is possible, by passing literals, to create such an object. In which case, most methods, when called with an Inet6Address will throw an Exception.

    Sockets

    Sockets are means to establish a communication link between machines over the network. The java.net package provides 4 kinds of Sockets:

    • Socket is a TCP client API, and will typically be used to connect to a remote host.
    • ServerSocket is a TCP server API, and will typically accept connections from client sockets.
    • DatagramSocket is a UDP endpoint API and is used to send and receivedatagram packets.
    • MulticastSocket is a subclass of DatagramSocket used when dealing with multicast groups.

    Sending and receiving with TCP sockets is done through InputStreams and OutputStreams which can be obtained via the Socket.getInputStream() and Socket.getOutputStream() methods.

    Interfaces

    The NetworkInterface class provides APIs to browse and query all the networking interfaces (e.g. ethernet connection or PPP endpoint) of the local machine. It is through that class that you can check if any of the local interfaces is configured to support IPv6.

    Note, all conforming implementations must support at least one NetworkInterface object, which must either be connected to a network, or be a «loopback» interface that can only communicate with entities on the same machine.

    High level API

    • URI is the class representing a Universal Resource Identifier, as specified in RFC 2396. As the name indicates, this is just an Identifier and doesn’t provide directly the means to access the resource.
    • URL is the class representing a Universal Resource Locator, which is both an older concept for URIs and a means to access the resources.
    • URLConnection is created from a URL and is the communication link used to access the resource pointed by the URL. This abstract class will delegate most of the work to the underlying protocol handlers like http or https.
    • HttpURLConnection is a subclass of URLConnection and provides some additional functionalities specific to the HTTP protocol. This API has been superseded by the newer HTTP Client API.

    The recommended usage is to use URI to identify resources, then convert it into a URL when it is time to access the resource. From that URL, you can either get the URLConnection for fine control, or get directly the InputStream.

    URI uri = new URI("http://www.example.com/"); URL url = uri.toURL(); InputStream in = url.openStream();

    Protocol Handlers

    As mentioned, URL and URLConnection rely on protocol handlers which must be present, otherwise an Exception is thrown. This is the major difference with URIs which only identify resources, and therefore don’t need to have access to the protocol handler. So, while it is possible to create an URI with any kind of protocol scheme (e.g. myproto://myhost.mydomain/resource/ ), a similar URL will try to instantiate the handler for the specified protocol; if it doesn’t exist an exception will be thrown.

    By default the protocol handlers are loaded dynamically from the default location. It is, however, possible to deploy additional protocols handlers as services . Service providers of type URLStreamHandlerProvider are located at runtime, as specified in the URL constructor.

    Additional Specification

    Источник

    Руководство по Java 9. HTTP 2.

    В данной статье мы рассмотрим поддержку HTTP 2 в Java 9. HTTP 2 – это новая версия HTTP, в котором акцент сделан на то, как именно данные упаковываются и передаются от клиента к серверу и наоборот.

    Среди преимуществ HTTP 2 можно выделить следующие:

    • Мультиплексирование
      HTTP 2 может отправлять несколько запросов данных параллельно, используя одно TCP соединение. В HTTP 1.1 мы не можем использовать более 6 открытых соединений одновременно.
    • Замена текста на Binary
    • Server Push
      При работе с HTTP 1.1 страницы пересылаются на клиент (браузеру) и он должен парсить HTML. Во время этого процесса, клиент может запрашивать дополнительные данные от сервера. В HTTP 2 сервер может отправлять эти данные без запроса от клиента

    В новом API мы имеем возможность работать с HTTP соединениями, используя 3 класса:

    • HttpRequest
      используется для создания HTTP запроса от клиента к серверу
    • HttpResponse
      содержит HTTP ответ от сервера
    • HttpClient
      отвечает за обработку и отправку HTTP запросов

    Рассмотрим небольшой пример:

    Добавим в корневую директорию файл module-info.java:

    Это необходимо для импорта в наш текущий модуль jdk.incubator.httpclient.

    package net.proselyte.java9; import jdk.incubator.http.*; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; public class Http2Demo < public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException < HttpClient httpClient = HttpClient.newHttpClient(); System.out.println("httpClient version: " + httpClient.version()); HttpRequest httpRequest = HttpRequest.newBuilder().uri(new URI("https://www.google.com/")).GET().build(); HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandler.asString()); System.out.println("httpResponse body: " + httpResponse.body()); System.out.println("httpResponse body: " + httpResponse.statusCode()); >> 

    В результате работы программы мы получим, примерно, следующий результат:

     WARNING: Using incubator modules: jdk.incubator.httpclient httpClient version: HTTP_2 httpResponse body: #gbar,#guser#gbar#guser.gbh,.gbd.gbh@media all#gbar>a.gb1,a.gb4a.gb1,a.gb4.gbi .gb4.gbf .gb4 body,td,a,p,.hbody#gogtd.gac_m tdform.h.q.ts td.tsem.lst.gsfi,.lst.gsfs.dsinputa.gb1,a.gb2,a.gb3,a.gb4bodyaa:hover,a:active.fl aa:visiteda.gb1,a.gb4a.gb3:hover#ghead a.gb2:hover.sblc.sblc a.lsbb.lsbb.ftl,#fll a.lsb.lsb:active.lst:focus.tiah  
    Зображення Карти YouTube Новини Gmail Диск Календар Більше »


     

    Розширений пошукМовні інструменти

    #gws-output-pages-elements-homepage_additional_languages__als#SIvCob#SIvCob a.H6sW5.z4hgWe
    Мова Google: русский
    РекламаРішення для бізнесуУсе про GoogleGoogle.com.ua

    © 2018

    Кроме того, мы имеем возможность работать с асинхронными запросами:

     package net.proselyte.java9; import jdk.incubator.http.HttpClient; import jdk.incubator.http.HttpRequest; import jdk.incubator.http.HttpResponse; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class Http2DemoAsync < public static void main(String[] args) throws URISyntaxException, InterruptedException, ExecutionException < HttpClient httpClient = HttpClient.newHttpClient(); System.out.println("httpClient version: " + httpClient.version()); HttpRequest httpRequest = HttpRequest.newBuilder().uri(new URI("https://www.google.com/")).GET().build(); CompletableFuturehttpResponse = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandler.asString()); if (httpResponse.isDone()) < System.out.println("httpResponse body: " + httpResponse.get().body()); System.out.println("httpResponse body: " + httpResponse.get().statusCode()); >else < System.out.println("Response is not completed. "); httpResponse.cancel(true); >> > 

    В результате выполнения данного примера, мы получим:

     WARNING: Using incubator modules: jdk.incubator.httpclient httpClient version: HTTP_2 Response is not completed. 

    На этом мы заканчиваем обор поддержки HTTP 2 в Java 9 и цикл в целом.

    Источник

Оцените статью