Настройки connectionrequest что это

от admin

Настройки connectionrequest что это

Though every TR-069 session is initiated by the CPE endpoint, sometimes it’s necessary for the ACS to request that the CPE contact it immediately. To do this, TR-069 defines a Connection Request mechanism in CWMP, which allows the ACS to stimulate the CPE to begin a session.

The most basic Connection Request is a simple HTTP GET on a URL defined by the CPE, defined in the ConnectionRequestURL parameter of the ManagementServer object in the CPE data model. This parameter is included in every Inform the CPE makes, to ensure that the ACS knows the URL.

This HTTP GET is authenticated by the CPE using a username and password specific to the ACS. Usually, the ACS will set this username and password after a CPE contacts it for the first time. These are defined in the ConnectionRequestUsername and ConnectionRequestPassword parameters in the ManagementServer object.

Once the HTTP GET is authenticated, the CPE sends an HTTP Response with a 200 OK or 204 “No Content” status code. This tells the ACS that the CPE received and understood the request. The response needs to happen immediately, and before any session triggered by the request occurs.

If the CPE receives more than one ConnectionRequest before the first session occurs, it must still respond to them, but only begin one Session as a result.

If CPE is already in a Session with the ACS when it receives a ConnectionRequest, it can’t terminate that Session prematurely. Instead, it can send a 503 “Service Unavailable” status code, or wait for the current session to finish before starting the requested Session.

When it’s ready, CPE starts the new session within 30 seconds of receiving the Connection Request, and includes the “6 CONNECTION REQUEST” event code in its Inform call. The session then proceeds as normal.

There’s one caveat to ConnectionRequests — they require that the CPE can be reached by the ACS over HTTP. For endpoints that may reside behind a Gateway, this is not the case, thanks to Network Address Translation or Firewall rules. To get around this, TR-069 Annex K defines a way to perform [Connection Requests over XMPP]().

Building or deploying TR-069?

Develop your solution even faster with the industry standard in automated, expert testing.

Настройки connectionrequest что это

Настройки connectionrequest что это

Though every TR-069 session is initiated by the CPE endpoint, sometimes it’s necessary for the ACS to request that the CPE contact it immediately. To do this, TR-069 defines a Connection Request mechanism in CWMP, which allows the ACS to stimulate the CPE to begin a session.

The most basic Connection Request is a simple HTTP GET on a URL defined by the CPE, defined in the ConnectionRequestURL parameter of the ManagementServer object in the CPE data model. This parameter is included in every Inform the CPE makes, to ensure that the ACS knows the URL.

This HTTP GET is authenticated by the CPE using a username and password specific to the ACS. Usually, the ACS will set this username and password after a CPE contacts it for the first time. These are defined in the ConnectionRequestUsername and ConnectionRequestPassword parameters in the ManagementServer object.

Once the HTTP GET is authenticated, the CPE sends an HTTP Response with a 200 OK or 204 “No Content” status code. This tells the ACS that the CPE received and understood the request. The response needs to happen immediately, and before any session triggered by the request occurs.

If the CPE receives more than one ConnectionRequest before the first session occurs, it must still respond to them, but only begin one Session as a result.

If CPE is already in a Session with the ACS when it receives a ConnectionRequest, it can’t terminate that Session prematurely. Instead, it can send a 503 “Service Unavailable” status code, or wait for the current session to finish before starting the requested Session.

When it’s ready, CPE starts the new session within 30 seconds of receiving the Connection Request, and includes the “6 CONNECTION REQUEST” event code in its Inform call. The session then proceeds as normal.

There’s one caveat to ConnectionRequests — they require that the CPE can be reached by the ACS over HTTP. For endpoints that may reside behind a Gateway, this is not the case, thanks to Network Address Translation or Firewall rules. To get around this, TR-069 Annex K defines a way to perform [Connection Requests over XMPP]().

Building or deploying TR-069?

Develop your solution even faster with the industry standard in automated, expert testing.

ConnectionRequest

Simple data container encapsulating a request to some entity to create a new Connection .

Summary

Inherited constants

Descriptor bit used with describeContents() : indicates that the Parcelable object’s flattened representation includes a file descriptor.

Flag for use with writeToParcel(Parcel, int) : the object being written is a return value, that is the result of a function such as » Parcelable someFunction() «, » void someFunction(out Parcelable) «, or » void someFunction(inout Parcelable) «.

Fields
Public constructors
Public methods

Describe the kinds of special objects contained in this Parcelable instance’s marshaled representation.

The account which should be used to place the call.

The handle (e.g., phone number) to which the Connection is to connect.

Application-specific extra data.

Describes the video states supported by the client requesting the connection.

Returns a string representation of the object.

Flatten this object in to a Parcel.

Inherited methods

Creates and returns a copy of this object.

Indicates whether some other object is «equal to» this one.

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Returns the runtime class of this Object .

Returns a hash code value for the object.

Wakes up a single thread that is waiting on this object’s monitor.

Wakes up all threads that are waiting on this object’s monitor.

Returns a string representation of the object.

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

Describe the kinds of special objects contained in this Parcelable instance’s marshaled representation.

Flatten this object in to a Parcel.

Fields

CREATOR

Public constructors

ConnectionRequest
Parameters
accountHandle PhoneAccountHandle : The accountHandle which should be used to place the call.
handle Uri : The handle (e.g., phone number) to which the Connection is to connect.
extras Bundle : Application-specific extra data.
ConnectionRequest
Parameters
accountHandle PhoneAccountHandle : The accountHandle which should be used to place the call.
handle Uri : The handle (e.g., phone number) to which the Connection is to connect.
extras Bundle : Application-specific extra data.
videoState int : Determines the video state for the connection.

Public methods

describeContents

Describe the kinds of special objects contained in this Parcelable instance’s marshaled representation. For example, if the object will include a file descriptor in the output of writeToParcel(Parcel, int) , the return value of this method must include the CONTENTS_FILE_DESCRIPTOR bit.

Returns
int a bitmask indicating the set of special object types marshaled by this Parcelable object instance.
getAccountHandle

The account which should be used to place the call.

Returns
PhoneAccountHandle
getAddress

The handle (e.g., phone number) to which the Connection is to connect.

Returns
Uri
getExtras

Application-specific extra data. Used for passing back information from an incoming call Intent , and for any proprietary extensions arranged between a client and servant ConnectionService which agree on a vocabulary for such data.

Returns
Bundle
getVideoState

Describes the video states supported by the client requesting the connection. Valid values: STATE_AUDIO_ONLY , STATE_BIDIRECTIONAL , STATE_TX_ENABLED , STATE_RX_ENABLED .

Returns
int The video state for the connection.
toString

Returns a string representation of the object. In general, the toString method returns a string that «textually represents» this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character ` @ ‘, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

Постоянное соединение Http и пул соединений HttpClient

В результате был также разработан протокол HTTP, и повторное использование сокетных соединений выполняется через постоянные соединения.

2. Keep-Alive HTTP / 1.0 +

Клиенты, использующие HTTP / 1.0, добавляют в заголовок «Connection: Keep-Alive», запрашивая у сервера держать соединение открытым. Если сервер хочет оставить это соединение открытым, он включит в ответ тот же заголовок. Если ответ не содержит заголовка «Connection: Keep-Alive», клиент будет считать, что сервер не поддерживает keep-alive, и закроет текущее соединение после отправки ответного сообщения.

Русские Блоги

Постоянное соединение Http и пул соединений HttpClient

1. История

Протокол HTTP — это протокол без сохранения состояния, то есть каждый запрос не зависит друг от друга. Следовательно, его первоначальная реализация состоит в том, что каждый http-запрос открывает соединение через сокет tcp и закрывает это соединение после завершения взаимодействия.

HTTP-протокол является полнодуплексным протоколом, поэтому для установления и отключения требуется три рукопожатия и четыре волны. Очевидно, что в этой схеме каждый раз, когда отправляется запрос Http, будет потребляться много дополнительных ресурсов, а именно установление и уничтожение соединения.

В результате был также разработан протокол HTTP, и повторное использование сокетных соединений выполняется через постоянные соединения.

Как видно из рисунка:

    В последовательном соединении соединение должно быть открыто и закрыто для каждого взаимодействия

В постоянном соединении первое взаимодействие откроет соединение, и соединение не будет закрыто после завершения взаимодействия. Следующее взаимодействие сохранит процесс установления соединения.

Существует две реализации постоянного подключения: поддержка HTTP / 1.0 + и постоянное подключение HTTP / 1.1.

2. Keep-Alive HTTP / 1.0 +

С 1996 года многие браузеры и серверы HTTP / 1.0 расширили протокол, который является расширенным протоколом «keep-alive».

Обратите внимание, что этот расширенный протокол выглядит как «экспериментальное постоянное соединение», которое дополняет 1.0. Keep-alive больше не используется и не объясняется в последней спецификации HTTP / 1.1, но многие приложения продолжаются.

Клиенты, использующие HTTP / 1.0, добавляют в заголовок «Connection: Keep-Alive», запрашивая у сервера держать соединение открытым. Если сервер хочет оставить это соединение открытым, он включит в ответ тот же заголовок. Если ответ не содержит заголовка «Connection: Keep-Alive», клиент будет считать, что сервер не поддерживает keep-alive, и закроет текущее соединение после отправки ответного сообщения.

Посредством дополнительного протокола keep-alive устанавливается постоянное соединение между клиентом и сервером, но все еще существуют некоторые проблемы:

  1. Keep-alive не является стандартным протоколом в HTTP / 1.0, и клиент должен отправить Connection: Keep-Alive, чтобы активировать соединение keep-alive.
  2. Прокси-сервер может не поддерживать keep-alive, потому что некоторые прокси являются «слепой ретранслятором» и не могут понять смысл заголовка, но пересылают заголовок один за другим. Таким образом, это может привести к тому, что клиент и сервер будут поддерживать соединение, но прокси-сервер не принимает данные о соединении.

Три, HTTP / 1.1 постоянное соединение

HTTP / 1.1 заменяет Keep-Alive постоянным соединением.

HTTP / 1.1 соединения являются постоянными соединениями по умолчанию. Если вы хотите явно закрыть, вам нужно добавить заголовок Connection: Close к сообщению. То есть в HTTP / 1.1 все соединения мультиплексированы.

Однако, как и Keep-Alive, неактивные постоянные соединения также могут быть закрыты клиентом и сервером в любое время. Не отправка Connection: Close не означает, что сервер обещает держать соединение открытым всегда.

В-четвертых, как HttpClient генерирует постоянные соединения

HttpClien использует пул соединений для управления удерживаемыми соединениями. По тому же каналу TCP соединение можно использовать повторно. HttpClient использует пул соединений для сохранения соединения.

На самом деле технология «бассейн» является универсальным дизайном, и ее дизайнерские идеи не сложны:

  1. Соединение устанавливается, когда соединение используется впервые
  2. Соответствующее соединение не закрывается в конце, а возвращается в пул
  3. Следующее соединение с той же целью может получить доступное соединение из пула
  4. Регулярно убирайте просроченные соединения

Все пулы соединений следуют этой идее, но мы рассмотрим исходный код HttpClient и сосредоточимся на двух моментах:

  1. Конкретная схема проектирования пула соединений для последующего использования пользовательского пула соединений
  2. Как соответствовать протоколу HTTP, то есть реализации теоретической абстракции в коде

4.1 Реализация пула соединений HttpClient (версия 4.5)

Обработка постоянных соединений в HttpClient может быть сосредоточена в следующем коде: ниже извлекаются связанные с пулом соединения части из MainClientExec и удаляются другие части:

Здесь мы видим, что обработка соединения в процессе запроса Http согласуется со спецификацией протокола. Здесь мы продолжим конкретную реализацию.

PoolingHttpClientConnectionManager является менеджером соединений по умолчанию для HttpClient. Сначала получите запрос на соединение через requestConnection (). Обратите внимание, что это не соединение.

Вы можете видеть, что возвращенный объект ConnectionRequest на самом деле содержит Future <CPoolEntry>, а CPoolEntry — реальный экземпляр соединения, управляемый пулом соединений.

На что мы должны обратить внимание из приведенного выше кода:

Future< CPoolEntry > future = this.pool.lease(route, state, null)

Как получить асинхронное соединение из пула соединений CPool, Future <CPoolEntry>

HttpClientConnection conn = leaseConnection(future, timeout, tunit)

Как получить реальное соединение HttpClientConnection через асинхронное соединение Future <CPoolEntry>

4.2 Future< CPoolEntry >

  1. Максимальное количество пулов соединений [ниже приведено количество больших пулов соединений]: AbstractConnPool # maxTotal
  2. Номер соединения по умолчанию для максимального маршрута (IP + PORT) [ниже приведено количество небольших пулов соединений]: AbstractConnPool # defaultMaxPerRoute

Укажите количество соединений маршрутизации, которое может быть установлено с помощью AbstractConnPool # setMaxPerRoute. Если нет, используйте значение по умолчанию в 2.

maxTotal >= ∑ d e f a u l t M a x P e r R o u t e

Посмотрите, как CPool выпускает Future <CPoolEntry>,AbstractConnPoolОсновной код, полученный в классе, выглядит следующим образом:

Приведенная выше логика кода имеет несколько важных моментов:

  • Пул соединений имеет максимальное количество соединений, каждый маршрут соответствует небольшому пулу соединений, а также существует максимальное количество соединений
  • Независимо от того, является ли это большим пулом соединений или небольшим пулом соединений, при превышении этого числа некоторые соединения должны быть освобождены через LRU
  • Если вы получаете доступное соединение, вернитесь на верхний уровень для использования
  • Если доступное соединение не получено, HttpClient определит, превысил ли текущий пул соединений маршрута максимальное число, а если максимальное число не достигнуто, будет создано новое соединение и помещено в пул.
  • Если верхний предел достигнут, подождите в очереди, дождитесь достижения семафора, повторно запишите его и сгенерируйте исключение тайм-аута, если он не ждет
  • Для получения соединения через пул потоков необходимо заблокировать через ReetrantLock для обеспечения безопасности потока

Пока что программа получила пригодный для использования экземпляр CPoolEntry или выдает исключение для завершения программы.

4.3 HttpClientConnection

5. Как HttpClient повторно использует постоянные соединения?

В предыдущей главе мы увидели, что HttpClient получает соединение через пул соединений и получает его из пула, когда соединение требуется.

Соответствует вопросу в главе 3:

  1. Соединение устанавливается, когда соединение используется впервые
  2. Соответствующее соединение не закрывается в конце, а возвращается в пул
  3. Следующее соединение с той же целью может получить доступное соединение из пула
  4. Регулярно убирайте просроченные соединения

В главе 4 мы увидели, как HttpClient обрабатывает проблемы 1 и 3. Так как же решается вторая проблема?

То есть, как HttpClient определяет, должно ли соединение быть закрыто после использования или помещено в пул для повторного использования другими? Посмотрите на код MainClientExec еще раз

Можно видеть, что после того, как запрос сделан с использованием соединения, существует стратегия повторного подключения, чтобы определить, следует ли повторно использовать соединение. Если оно будет использоваться повторно, оно будет передано HttpClientConnectionManager для размещения в пуле после завершения.

Так в чем же логика стратегии повторного использования соединения?

Взгляните на стратегию повторного использования родительского класса

В заключение:

  1. Если заголовок запроса содержит Connection: Close, повторное использование не требуется
  2. Если в ответе есть заголовок ответа, передается кодировка: «Transfer-Encoding», а значение не является chunked encoding: chunked. Нет повторного использования
  3. Если длина заголовка ответа Content-Length в ответе установлена ​​неправильно, повторное использование не требуется
  4. Если заголовок ответа содержит Connection: Close, не используйте повторно
  5. Если у ответа нет заголовка ответа Connection, но есть заголовок ответа Proxy-Connection: Close, не используйте повторно
  6. Если заголовок ответа содержит Connection: Keep-Alive, используйте повторно
  7. Если ответ не имеет заголовка ответа Connection, но имеет заголовок ответа Proxy-Connection: Keep-Alive, используйте повторно
  8. В случае отсутствия попаданий используйте повторно, если версия HTTP выше 1.0

Как видно из кода, его стратегия реализации согласуется с ограничениями уровня протокола в главах 2 и 3.

Как HttpClient очищает устаревшие соединения

Перед использованием HttpClient 4.4 при повторном использовании соединений из пула соединений они проверяются на срок действия, а срок действия истекает.

Более поздняя версия отличается. Будет отдельный поток для сканирования соединений в пуле соединений, и он будет очищаться, когда будет обнаружено, что время с момента последнего использования превышает установленное время. Период ожидания по умолчанию составляет 2 секунды.

Если пул соединений является общим (connManagerShared = true), то есть несколько клиентов http совместно используют пул соединений, эти две конфигурации недопустимы.

Можно видеть, что при сборке HttpClientBuilder, если указана функция очистки, будет создан и запущен поток очистки пула соединений.

Chapter 2. Connection management

The process of establishing a connection from one host to another is quite complex and involves multiple packet exchanges between two endpoints, which can be quite time consuming. The overhead of connection handshaking can be significant, especially for small HTTP messages. One can achieve a much higher data throughput if open connections can be re-used to execute multiple requests.

HTTP/1.1 states that HTTP connections can be re-used for multiple requests per default. HTTP/1.0 compliant endpoints can also use a mechanism to explicitly communicate their preference to keep connection alive and use it for multiple requests. HTTP agents can also keep idle connections alive for a certain period time in case a connection to the same target host is needed for subsequent requests. The ability to keep connections alive is usually refered to as connection persistence. HttpClient fully supports connection persistence.

2.2. HTTP connection routing

HttpClient is capable of establishing connections to the target host either directly or via a route that may involve multiple intermediate connections — also referred to as hops. HttpClient differentiates connections of a route into plain, tunneled and layered. The use of multiple intermediate proxies to tunnel connections to the target host is referred to as proxy chaining.

Plain routes are established by connecting to the target or the first and only proxy. Tunnelled routes are established by connecting to the first and tunnelling through a chain of proxies to the target. Routes without a proxy cannot be tunnelled. Layered routes are established by layering a protocol over an existing connection. Protocols can only be layered over a tunnel to the target, or over a direct connection without proxies.

2.2.1. Route computation

The RouteInfo interface represents information about a definitive route to a target host involving one or more intermediate steps or hops. HttpRoute is a concrete implementation of the RouteInfo , which cannot be changed (is immutable). HttpTracker is a mutable RouteInfo implementation used internally by HttpClient to track the remaining hops to the ultimate route target. HttpTracker can be updated after a successful execution of the next hop towards the route target. HttpRouteDirector is a helper class that can be used to compute the next step in a route. This class is used internally by HttpClient.

HttpRoutePlanner is an interface representing a strategy to compute a complete route to a given target based on the execution context. HttpClient ships with two default HttpRoutePlanner implementations. SystemDefaultRoutePlanner is based on java.net.ProxySelector . By default, it will pick up the proxy settings of the JVM, either from system properties or from the browser running the application. The DefaultProxyRoutePlanner implementation does not make use of any Java system properties, nor any system or browser proxy settings. It always computes routes via the same default proxy.

2.2.2. Secure HTTP connections

HTTP connections can be considered secure if information transmitted between two connection endpoints cannot be read or tampered with by an unauthorized third party. The SSL/TLS protocol is the most widely used technique to ensure HTTP transport security. However, other encryption techniques could be employed as well. Usually, HTTP transport is layered over the SSL/TLS encrypted connection.

2.3. HTTP connection managers

2.3.1. Managed connections and connection managers

HTTP connections are complex, stateful, thread-unsafe objects which need to be properly managed to function correctly. HTTP connections can only be used by one execution thread at a time. HttpClient employs a special entity to manage access to HTTP connections called HTTP connection manager and represented by the HttpClientConnectionManager interface. The purpose of an HTTP connection manager is to serve as a factory for new HTTP connections, to manage life cycle of persistent connections and to synchronize access to persistent connections making sure that only one thread can have access to a connection at a time. Internally HTTP connection managers work with instances of ManagedHttpClientConnection acting as a proxy for a real connection that manages connection state and controls execution of I/O operations. If a managed connection is released or get explicitly closed by its consumer the underlying connection gets detached from its proxy and is returned back to the manager. Even though the service consumer still holds a reference to the proxy instance, it is no longer able to execute any I/O operations or change the state of the real connection either intentionally or unintentionally.

This is an example of acquiring a connection from a connection manager:

The connection request can be terminated prematurely by calling ConnectionRequest#cancel() if necessary. This will unblock the thread blocked in the ConnectionRequest#get() method.

2.3.2. Simple connection manager

BasicHttpClientConnectionManager is a simple connection manager that maintains only one connection at a time. Even though this class is thread-safe it ought to be used by one execution thread only. BasicHttpClientConnectionManager will make an effort to reuse the connection for subsequent requests with the same route. It will, however, close the existing connection and re-open it for the given route, if the route of the persistent connection does not match that of the connection request. If the connection has been already been allocated, then java.lang.IllegalStateException is thrown.

This connection manager implementation should be used inside an EJB container.

2.3.3. Pooling connection manager

PoolingHttpClientConnectionManager is a more complex implementation that manages a pool of client connections and is able to service connection requests from multiple execution threads. Connections are pooled on a per route basis. A request for a route for which the manager already has a persistent connection available in the pool will be serviced by leasing a connection from the pool rather than creating a brand new connection.

PoolingHttpClientConnectionManager maintains a maximum limit of connections on a per route basis and in total. Per default this implementation will create no more than 2 concurrent connections per given route and no more 20 connections in total. For many real-world applications these limits may prove too constraining, especially if they use HTTP as a transport protocol for their services.

This example shows how the connection pool parameters can be adjusted:

2.3.4. Connection manager shutdown

When an HttpClient instance is no longer needed and is about to go out of scope it is important to shut down its connection manager to ensure that all connections kept alive by the manager get closed and system resources allocated by those connections are released.

2.4. Multithreaded request execution

When equipped with a pooling connection manager such as PoolingClientConnectionManager , HttpClient can be used to execute multiple requests simultaneously using multiple threads of execution.

The PoolingClientConnectionManager will allocate connections based on its configuration. If all connections for a given route have already been leased, a request for a connection will block until a connection is released back to the pool. One can ensure the connection manager does not block indefinitely in the connection request operation by setting ‘http.conn-manager.timeout’ to a positive value. If the connection request cannot be serviced within the given time period ConnectionPoolTimeoutException will be thrown.

While HttpClient instances are thread safe and can be shared between multiple threads of execution, it is highly recommended that each thread maintains its own dedicated instance of HttpContext .

2.5. Connection eviction policy

One of the major shortcomings of the classic blocking I/O model is that the network socket can react to I/O events only when blocked in an I/O operation. When a connection is released back to the manager, it can be kept alive however it is unable to monitor the status of the socket and react to any I/O events. If the connection gets closed on the server side, the client side connection is unable to detect the change in the connection state (and react appropriately by closing the socket on its end).

HttpClient tries to mitigate the problem by testing whether the connection is ‘stale’, that is no longer valid because it was closed on the server side, prior to using the connection for executing an HTTP request. The stale connection check is not 100% reliable. The only feasible solution that does not involve a one thread per socket model for idle connections is a dedicated monitor thread used to evict connections that are considered expired due to a long period of inactivity. The monitor thread can periodically call ClientConnectionManager#closeExpiredConnections() method to close all expired connections and evict closed connections from the pool. It can also optionally call ClientConnectionManager#closeIdleConnections() method to close all connections that have been idle over a given period of time.

2.6. Connection keep alive strategy

The HTTP specification does not specify how long a persistent connection may be and should be kept alive. Some HTTP servers use a non-standard Keep-Alive header to communicate to the client the period of time in seconds they intend to keep the connection alive on the server side. HttpClient makes use of this information if available. If the Keep-Alive header is not present in the response, HttpClient assumes the connection can be kept alive indefinitely. However, many HTTP servers in general use are configured to drop persistent connections after a certain period of inactivity in order to conserve system resources, quite often without informing the client. In case the default strategy turns out to be too optimistic, one may want to provide a custom keep-alive strategy.

2.7. Connection socket factories

HTTP connections make use of a java.net.Socket object internally to handle transmission of data across the wire. However they rely on the ConnectionSocketFactory interface to create, initialize and connect sockets. This enables the users of HttpClient to provide application specific socket initialization code at runtime. PlainConnectionSocketFactory is the default factory for creating and initializing plain (unencrypted) sockets.

The process of creating a socket and that of connecting it to a host are decoupled, so that the socket could be closed while being blocked in the connect operation.

2.7.1. Secure socket layering

LayeredConnectionSocketFactory is an extension of the ConnectionSocketFactory interface. Layered socket factories are capable of creating sockets layered over an existing plain socket. Socket layering is used primarily for creating secure sockets through proxies. HttpClient ships with SSLSocketFactory that implements SSL/TLS layering. Please note HttpClient does not use any custom encryption functionality. It is fully reliant on standard Java Cryptography (JCE) and Secure Sockets (JSEE) extensions.

2.7.2. Integration with connection manager

Custom connection socket factories can be associated with a particular protocol scheme as as HTTP or HTTPS and then used to create a custom connection manager.

2.7.3. SSL/TLS customization

HttpClient makes use of SSLConnectionSocketFactory to create SSL connections. SSLConnectionSocketFactory allows for a high degree of customization. It can take an instance of javax.net.ssl.SSLContext as a parameter and use it to create custom configured SSL connections.

Customization of SSLConnectionSocketFactory implies a certain degree of familiarity with the concepts of the SSL/TLS protocol, a detailed explanation of which is out of scope for this document. Please refer to the Java™ Secure Socket Extension (JSSE) Reference Guide for a detailed description of javax.net.ssl.SSLContext and related tools.

2.7.4. Hostname verification

In addition to the trust verification and the client authentication performed on the SSL/TLS protocol level, HttpClient can optionally verify whether the target hostname matches the names stored inside the server’s X.509 certificate, once the connection has been established. This verification can provide additional guarantees of authenticity of the server trust material. The javax.net.ssl.HostnameVerifier interface represents a strategy for hostname verification. HttpClient ships with two javax.net.ssl.HostnameVerifier implementations. Important: hostname verification should not be confused with SSL trust verification.

DefaultHostnameVerifier : The default implementation used by HttpClient is expected to be compliant with RFC 2818. The hostname must match any of alternative names specified by the certificate, or in case no alternative names are given the most specific CN of the certificate subject. A wildcard can occur in the CN, and in any of the subject-alts.

NoopHostnameVerifier : This hostname verifier essentially turns hostname verification off. It accepts any SSL session as valid and matching the target host.

Per default HttpClient uses the DefaultHostnameVerifier implementation. One can specify a different hostname verifier implementation if desired

As of version 4.4 HttpClient uses the public suffix list kindly maintained by Mozilla Foundation to make sure that wildcards in SSL certificates cannot be misused to apply to multiple domains with a common top-level domain. HttpClient ships with a copy of the list retrieved at the time of the release. The latest revision of the list can found at https://publicsuffix.org/list/. It is highly adviseable to make a local copy of the list and download the list no more than once per day from its original location.

One can disable verification against the public suffic list by using null matcher.

2.8. HttpClient proxy configuration

Even though HttpClient is aware of complex routing schemes and proxy chaining, it supports only simple direct or one hop proxy connections out of the box.

The simplest way to tell HttpClient to connect to the target host via a proxy is by setting the default proxy parameter:

One can also instruct HttpClient to use the standard JRE proxy selector to obtain proxy information:

Alternatively, one can provide a custom RoutePlanner implementation in order to have a complete control over the process of HTTP route computation:

Читать:
Как посчитать количество дат в столбце excel

Похожие статьи