Class Session

All Implemented Interfaces:
Proxy

@Generated("org.javagi.JavaGI") public class Session extends GObject

Soup session state object.

Session is the object that controls client-side HTTP. A Session encapsulates all of the state that libsoup is keeping on behalf of your program; cached HTTP connections, authentication information, etc. It also keeps track of various global options and features that you are using.

Most applications will only need a single Session; the primary reason you might need multiple sessions is if you need to have multiple independent authentication contexts. (Eg, you are connecting to a server and authenticating as two different users at different times; the easiest way to ensure that each Message is sent with the authentication information you intended is to use one session for the first user, and a second session for the other user.)

Additional Session functionality is provided by SessionFeature objects, which can be added to a session with addFeature(SessionFeature) or addFeatureByType(Type) For example, Logger provides support for logging HTTP traffic, ContentDecoder provides support for compressed response handling, and ContentSniffer provides support for HTML5-style response body content sniffing. Additionally, subtypes of Auth can be added as features, to add support for additional authentication types.

All SoupSessions are created with a AuthManager, and support for SOUP_TYPE_AUTH_BASIC and SOUP_TYPE_AUTH_DIGEST. Additionally, sessions using the plain Session class (rather than one of its deprecated subtypes) have a ContentDecoder by default.

Note that all async methods will invoke their callbacks on the thread-default context at the time of the function call.

  • Constructor Details

    • Session

      public Session(MemorySegment address)
      Create a Session instance for the provided memory address.
      Parameters:
      address - the memory address of the native object
    • Session

      public Session()
      Create a new Session.
  • Method Details

    • getType

      public static @Nullable Type getType()
      Get the GType of the Session class.
      Returns:
      the GType
    • getMemoryLayout

      public static MemoryLayout getMemoryLayout()
      The memory layout of the native struct.
      Returns:
      the memory layout
    • asParent

      protected Session asParent()
      Return this instance as if it were its parent type. Comparable to the Java super keyword, but ensures the parent typeclass is also used in native code.
      Overrides:
      asParent in class GObject
      Returns:
      the instance as if it were its parent type
    • withOptions

      public static Session withOptions(String optname1, Object... varargs)
      Creates a Session with the specified options.
      Parameters:
      optname1 - name of first property to set
      varargs - value of optname1, followed by additional property/value pairs
      Returns:
      the new session.
    • abort

      public void abort()
      Cancels all pending requests in this Session and closes all idle persistent connections.
    • addFeature

      public void addFeature(SessionFeature feature)

      Adds feature's functionality to session. You cannot add multiple features of the same GObject.Type to a session.

      See the main Session documentation for information on what features are present in sessions by default.

      Parameters:
      feature - an object that implements SoupSessionFeature
    • addFeatureByType

      public void addFeatureByType(Type featureType)

      If featureType is the type of a class that implements SessionFeature, this creates a new feature of that type and adds it to this Session as with addFeature(SessionFeature). You can use this when you don't need to customize the new feature in any way. Adding multiple features of the same featureType is not allowed.

      If featureType is not a SessionFeature type, this gives each existing feature on this Session the chance to accept featureType as a "subfeature". This can be used to add new Auth types, for instance.

      See the main Session documentation for information on what features are present in sessions by default.

      Parameters:
      featureType - a GType
    • getAcceptLanguage

      public @Nullable String getAcceptLanguage()
      Get the value used by this Session for the "Accept-Language" header on new requests.
      Returns:
      the accept language string
    • getAcceptLanguageAuto

      public boolean getAcceptLanguageAuto()
      Gets whether this Session automatically sets the "Accept-Language" header on new requests.
      Returns:
      true if this Session sets "Accept-Language" header automatically, or false otherwise.
    • getAsyncResultMessage

      public @Nullable Message getAsyncResultMessage(AsyncResult result)
      Gets the Message of the result asynchronous operation This is useful to get the Message of an asynchronous operation started by this Session from its Gio.AsyncReadyCallback.
      Parameters:
      result - the GAsyncResult passed to your callback
      Returns:
      a SoupMessage or null if result is not a valid this Session async operation result.
    • getFeature

      public @Nullable SessionFeature getFeature(Type featureType)
      Gets the feature in this Session of type featureType.
      Parameters:
      featureType - the GType of the feature to get
      Returns:
      a SoupSessionFeature, or null. The feature is owned by session.
    • getFeatureForMessage

      public @Nullable SessionFeature getFeatureForMessage(Type featureType, Message msg)
      Gets the feature in this Session of type featureType, provided that it is not disabled for msg.
      Parameters:
      featureType - the GType of the feature to get
      msg - a SoupMessage
      Returns:
      a SoupSessionFeature. The feature is owned by session.
    • getIdleTimeout

      public int getIdleTimeout()
      Get the timeout in seconds for idle connection lifetime currently used by session.
      Returns:
      the timeout in seconds
    • getLocalAddress

      public @Nullable InetSocketAddress getLocalAddress()
      Get the InetSocketAddress to use for the client side of connections in session.
      Returns:
      a GInetSocketAddress
    • getMaxConns

      public int getMaxConns()
      Get the maximum number of connections that this Session can open at once.
      Returns:
      the maximum number of connections
    • getMaxConnsPerHost

      public int getMaxConnsPerHost()
      Get the maximum number of connections that this Session can open at once to a given host.
      Returns:
      the maximum number of connections per host
    • getProxyResolver

      public @Nullable ProxyResolver getProxyResolver()
      Get the ProxyResolver currently used by session.
      Returns:
      a GProxyResolver or null if proxies are disabled in this Session
    • getRemoteConnectable

      public @Nullable SocketConnectable getRemoteConnectable()
      Gets the remote connectable if one set.
      Returns:
      the GSocketConnectable
    • getTimeout

      public int getTimeout()
      Get the timeout in seconds for socket I/O operations currently used by session.
      Returns:
      the timeout in seconds
    • getTlsDatabase

      public @Nullable TlsDatabase getTlsDatabase()
      Get the TlsDatabase currently used by session.
      Returns:
      a GTlsDatabase
    • getTlsInteraction

      public @Nullable TlsInteraction getTlsInteraction()
      Get the TlsInteraction currently used by session.
      Returns:
      a GTlsInteraction
    • getUserAgent

      public @Nullable String getUserAgent()
      Get the value used by this Session for the "User-Agent" header on new requests.
      Returns:
      the user agent string
    • hasFeature

      public boolean hasFeature(Type featureType)
      Tests if this Session has at a feature of type featureType (which can be the type of either a SessionFeature, or else a subtype of some class managed by another feature, such as Auth).
      Parameters:
      featureType - the GType of the class of features to check for
      Returns:
      true or false
    • preconnectAsync

      public void preconnectAsync(Message msg, int ioPriority, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback)

      Start a preconnection to msg.

      Once the connection is done, it will remain in idle state so that it can be reused by future requests. If there's already an idle connection for the given msg host, the operation finishes successfully without creating a new connection. If a new request for the given msg host is made while the preconnect is still ongoing, the request will take the ownership of the connection and the preconnect operation will finish successfully (if there's a connection error it will be handled by the request).

      The operation finishes when the connection is done or an error occurred.

      Parameters:
      msg - a SoupMessage
      ioPriority - the I/O priority of the request
      cancellable - a GCancellable
      callback - the callback to invoke when the operation finishes
    • preconnectFinish

      public boolean preconnectFinish(AsyncResult result) throws GErrorException
      Complete a preconnect async operation started with preconnectAsync(Message, int, Cancellable, AsyncReadyCallback).
      Parameters:
      result - the GAsyncResult passed to your callback
      Returns:
      true if the preconnect succeeded, or false in case of error.
      Throws:
      GErrorException - see GError
    • removeFeature

      public void removeFeature(SessionFeature feature)
      Removes feature's functionality from session.
      Parameters:
      feature - a feature that has previously been added to this Session
    • removeFeatureByType

      public void removeFeatureByType(Type featureType)
      Removes all features of type featureType (or any subclass of featureType) from session.
      Parameters:
      featureType - a GType
    • send

      public InputStream send(Message msg, @Nullable Cancellable cancellable) throws GErrorException

      Synchronously sends msg and waits for the beginning of a response.

      On success, a InputStream will be returned which you can use to read the response body. ("Success" here means only that an HTTP response was received and understood; it does not necessarily mean that a 2xx class status code was received.)

      If non-null, cancellable can be used to cancel the request; send(Message, Cancellable) will return a IOErrorEnum.CANCELLED error. Note that with requests that have side effects (eg, POST, PUT, DELETE) it is possible that you might cancel the request after the server acts on it, but before it returns a response, leaving the remote resource in an unknown state.

      If msg is requeued due to a redirect or authentication, the initial (3xx/401/407) response body will be suppressed, and send(Message, Cancellable) will only return once a final response has been received.

      Possible error domains include SessionError, Gio.IOErrorEnum, and Gio.TlsError which you may want to specifically handle.

      Parameters:
      msg - a SoupMessage
      cancellable - a GCancellable
      Returns:
      a GInputStream for reading the response body, or null on error.
      Throws:
      GErrorException - see GError
    • sendAndRead

      public byte[] sendAndRead(Message msg, @Nullable Cancellable cancellable) throws GErrorException

      Synchronously sends msg and reads the response body.

      On success, a GLib.Bytes will be returned with the response body. This function should only be used when the resource to be retrieved is not too long and can be stored in memory.

      See send(Message, Cancellable) for more details on the general semantics.

      Parameters:
      msg - a SoupMessage
      cancellable - a GCancellable
      Returns:
      a GBytes, or null on error.
      Throws:
      GErrorException - see GError
    • sendAndReadAsync

      public void sendAndReadAsync(Message msg, int ioPriority, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback)

      Asynchronously sends msg and reads the response body.

      When callback is called, then either msg has been sent, and its response body read, or else an error has occurred. This function should only be used when the resource to be retrieved is not too long and can be stored in memory. Call sendAndReadFinish(AsyncResult) to get a GLib.Bytes with the response body.

      See send(Message, Cancellable) for more details on the general semantics.

      Parameters:
      msg - a SoupMessage
      ioPriority - the I/O priority of the request
      cancellable - a GCancellable
      callback - the callback to invoke
    • sendAndReadFinish

      public byte[] sendAndReadFinish(AsyncResult result) throws GErrorException

      Gets the response to a sendAndReadAsync(Message, int, Cancellable, AsyncReadyCallback).

      If successful, returns a GLib.Bytes with the response body.

      Parameters:
      result - the GAsyncResult passed to your callback
      Returns:
      a GBytes, or null on error.
      Throws:
      GErrorException - see GError
    • sendAndSplice

      public long sendAndSplice(Message msg, OutputStream outStream, Set<OutputStreamSpliceFlags> flags, @Nullable Cancellable cancellable) throws GErrorException

      Synchronously sends msg and splices the response body stream into outStream.

      See send(Message, Cancellable) for more details on the general semantics.

      Parameters:
      msg - a SoupMessage
      outStream - a GOutputStream
      flags - a set of GOutputStreamSpliceFlags
      cancellable - a GCancellable
      Returns:
      a gssize containing the size of the data spliced, or -1 if an error occurred.
      Throws:
      GErrorException - see GError
      Since:
      3.4
    • sendAndSplice

      public long sendAndSplice(Message msg, OutputStream outStream, OutputStreamSpliceFlags flags, @Nullable Cancellable cancellable) throws GErrorException

      Synchronously sends msg and splices the response body stream into outStream.

      See send(Message, Cancellable) for more details on the general semantics.

      Parameters:
      msg - a SoupMessage
      outStream - a GOutputStream
      flags - a set of GOutputStreamSpliceFlags
      cancellable - a GCancellable
      Returns:
      a gssize containing the size of the data spliced, or -1 if an error occurred.
      Throws:
      GErrorException - see GError
      Since:
      3.4
    • sendAndSpliceAsync

      public void sendAndSpliceAsync(Message msg, OutputStream outStream, Set<OutputStreamSpliceFlags> flags, int ioPriority, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback)

      Asynchronously sends msg and splices the response body stream into outStream. When callback is called, then either msg has been sent and its response body spliced, or else an error has occurred.

      See send(Message, Cancellable) for more details on the general semantics.

      Parameters:
      msg - a SoupMessage
      outStream - a GOutputStream
      flags - a set of GOutputStreamSpliceFlags
      ioPriority - the I/O priority of the request
      cancellable - a GCancellable
      callback - the callback to invoke
      Since:
      3.4
    • sendAndSpliceAsync

      public void sendAndSpliceAsync(Message msg, OutputStream outStream, OutputStreamSpliceFlags flags, int ioPriority, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback)

      Asynchronously sends msg and splices the response body stream into outStream. When callback is called, then either msg has been sent and its response body spliced, or else an error has occurred.

      See send(Message, Cancellable) for more details on the general semantics.

      Parameters:
      msg - a SoupMessage
      outStream - a GOutputStream
      flags - a set of GOutputStreamSpliceFlags
      ioPriority - the I/O priority of the request
      cancellable - a GCancellable
      callback - the callback to invoke
      Since:
      3.4
    • sendAndSpliceFinish

      public long sendAndSpliceFinish(AsyncResult result) throws GErrorException
      Parameters:
      result - the GAsyncResult passed to your callback
      Returns:
      a gssize containing the size of the data spliced, or -1 if an error occurred.
      Throws:
      GErrorException - see GError
      Since:
      3.4
    • sendAsync

      public void sendAsync(Message msg, int ioPriority, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback)

      Asynchronously sends msg and waits for the beginning of a response.

      When callback is called, then either msg has been sent, and its response headers received, or else an error has occurred. Call sendFinish(AsyncResult) to get a InputStream for reading the response body.

      See send(Message, Cancellable) for more details on the general semantics.

      Parameters:
      msg - a SoupMessage
      ioPriority - the I/O priority of the request
      cancellable - a GCancellable
      callback - the callback to invoke
    • sendFinish

      public InputStream sendFinish(AsyncResult result) throws GErrorException

      Gets the response to a sendAsync(Message, int, Cancellable, AsyncReadyCallback) call.

      If successful returns a InputStream that can be used to read the response body.

      Parameters:
      result - the GAsyncResult passed to your callback
      Returns:
      a GInputStream for reading the response body, or null on error.
      Throws:
      GErrorException - see GError
    • setAcceptLanguage

      public void setAcceptLanguage(String acceptLanguage)

      Set the value to use for the "Accept-Language" header on Messages sent from session.

      If acceptLanguage is null then no "Accept-Language" will be included in requests. See Session:accept-language for more information.

      Parameters:
      acceptLanguage - the languages string
    • setAcceptLanguageAuto

      public void setAcceptLanguageAuto(boolean acceptLanguageAuto)

      Set whether this Session will automatically set the "Accept-Language" header on requests using a value generated from system languages based on GLib#getLanguageNames.

      See Session:accept-language-auto for more information.

      Parameters:
      acceptLanguageAuto - the value to set
    • setIdleTimeout

      public void setIdleTimeout(int timeout)

      Set a timeout in seconds for idle connection lifetime to be used by this Session on new connections.

      See Session:idle-timeout for more information.

      Parameters:
      timeout - a timeout in seconds
    • setProxyResolver

      public void setProxyResolver(@Nullable ProxyResolver proxyResolver)

      Set a ProxyResolver to be used by this Session on new connections.

      If proxyResolver is null then no proxies will be used. See Session:proxy-resolver for more information.

      Parameters:
      proxyResolver - a GProxyResolver or null
    • setTimeout

      public void setTimeout(int timeout)

      Set a timeout in seconds for socket I/O operations to be used by this Session on new connections.

      See Session:timeout for more information.

      Parameters:
      timeout - a timeout in seconds
    • setTlsDatabase

      public void setTlsDatabase(@Nullable TlsDatabase tlsDatabase)

      Set a TlsDatabase to be used by this Session on new connections.

      If tlsDatabase is null then certificate validation will always fail. See Session:tls-database for more information.

      Parameters:
      tlsDatabase - a GTlsDatabase
    • setTlsInteraction

      public void setTlsInteraction(@Nullable TlsInteraction tlsInteraction)

      Set a TlsInteraction to be used by this Session on new connections.

      If tlsInteraction is null then client certificate validation will always fail.

      See Session:tls-interaction for more information.

      Parameters:
      tlsInteraction - a GTlsInteraction
    • setUserAgent

      public void setUserAgent(String userAgent)

      Set the value to use for the "User-Agent" header on Messages sent from session.

      If userAgent has trailing whitespace, this Session will append its own product token (eg, libsoup/3.0.0) to the end of the header for you. If userAgent is null then no "User-Agent" will be included in requests. See Session:user-agent for more information.

      Parameters:
      userAgent - the user agent string
    • websocketConnectAsync

      public void websocketConnectAsync(Message msg, @Nullable String origin, @Nullable String @Nullable [] protocols, int ioPriority, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback)

      Asynchronously creates a WebsocketConnection to communicate with a remote server.

      All necessary WebSocket-related headers will be added to msg, and it will then be sent and asynchronously processed normally (including handling of redirection and HTTP authentication).

      If the server returns "101 Switching Protocols", then msg's status code and response headers will be updated, and then the WebSocket handshake will be completed. On success, websocketConnectFinish(AsyncResult) will return a new WebsocketConnection. On failure it will return a GError.

      If the server returns a status other than "101 Switching Protocols", then msg will contain the complete response headers and body from the server's response, and websocketConnectFinish(AsyncResult) will return WebsocketError.NOT_WEBSOCKET.

      Parameters:
      msg - SoupMessage indicating the WebSocket server to connect to
      origin - origin of the connection
      protocols - a null-terminated array of protocols supported
      ioPriority - the I/O priority of the request
      cancellable - a GCancellable
      callback - the callback to invoke
    • websocketConnectFinish

      public WebsocketConnection websocketConnectFinish(AsyncResult result) throws GErrorException

      Gets the WebsocketConnection response to a websocketConnectAsync(Message, String, String[], int, Cancellable, AsyncReadyCallback) call.

      If successful, returns a WebsocketConnection that can be used to communicate with the server.

      Parameters:
      result - the GAsyncResult passed to your callback
      Returns:
      a new SoupWebsocketConnection, or null on error.
      Throws:
      GErrorException - see GError
    • requestQueued

      protected void requestQueued(Message msg)
    • requestUnqueued

      protected void requestUnqueued(Message msg)
    • onRequestQueued

      Emitted when a request is queued on session.

      When sending a request, first Session::request-queued is emitted, indicating that the session has become aware of the request.

      After a connection is available to send the request various Message signals are emitted as the message is processed. If the message is requeued, it will emit Message::restarted, which will then be followed by other Message signals when the message is re-sent.

      Eventually, the message will emit Message::finished. Normally, this signals the completion of message processing. However, it is possible that the application will requeue the message from the "finished" handler. In that case the process will loop back.

      Eventually, a message will reach "finished" and not be requeued. At that point, the session will emit Session::request-unqueued to indicate that it is done with the message.

      To sum up: Session::request-queued and Session::request-unqueued are guaranteed to be emitted exactly once, but Message::finished (and all of the other Message signals) may be invoked multiple times for a given message.

      Parameters:
      handler - the signal handler
      Returns:
      a signal handler ID to keep track of the signal connection
      See Also:
    • emitRequestQueued

      public void emitRequestQueued(@Nullable Message msg)
      Emits the "request-queued" signal. See onRequestQueued(Session.RequestQueuedCallback).
    • onRequestUnqueued

      Emitted when a request is removed from session's queue, indicating that session is done with it.

      See Session::request-queued for a detailed description of the message lifecycle within a session.

      Parameters:
      handler - the signal handler
      Returns:
      a signal handler ID to keep track of the signal connection
      See Also:
    • emitRequestUnqueued

      public void emitRequestUnqueued(@Nullable Message msg)
      Emits the "request-unqueued" signal. See onRequestUnqueued(Session.RequestUnqueuedCallback).
    • builder

      public static Session.Builder<? extends Session.Builder> builder()
      A Session.Builder object constructs a Session with the specified properties. Use the various set...() methods to set properties, and finish construction with Session.Builder.build().
      Returns:
      the builder object