Standard library HTTP TCP and TLS

Networking, HTTP, and TLS

The klyn.net package provides validated URLs, immutable HTTP requests, blocking TCP sockets, and verified TLS. High-level HTTP and low-level socket APIs share explicit timeout and exception semantics.

Parse and Validate URLs
import klyn.net

url = URL("https://example.com:8443/articles?page=2#results")

assert url.protocol == "https"
assert url.host == "example.com"
assert url.effectivePort == 8443
assert url.path == "/articles"
assert url.query == "page=2"
assert url.fragment == "results"

Construction validates the URL and raises MalformedURLException for malformed input. effectivePort applies the protocol default when no explicit port is present.

Send HTTP Requests

HttpClient is synchronous. A timeout is expressed in milliseconds; 0u means no timeout. Always test response.ok or the exact status code before consuming a response body.

import klyn.collections
import klyn.net

client = HttpClient(timeout=5000u)
response = client.get(
    "https://api.example.com/status",
    {"Accept": "application/json"}
)

if not response.ok:
    throw ProtocolException(
        f"HTTP {response.statusCode} for {response.url}"
    )

document = response.json<SortedMap<String, Object>>()
print(document)

get(), post(), put(), patch(), and deleteRequest() cover common methods. A map or list body is serialized as JSON and the content type is added when the caller did not provide one.

Build Immutable Requests

HttpRequest copies its headers at construction. Methods beginning with with return a new request instead of mutating the original value.

import klyn.net

request = HttpRequest(
    "https://api.example.com/articles",
    "POST",
    body={"title": "Klyn networking"}
).withHeader("Accept", "application/json")

response = HttpClient(timeout=5000u).send(request)
print(response.statusCode)
Cancellation is explicit

send() blocks the calling thread. Another thread may call client.cancel() to cancel the active transfer. In a GUI, perform network I/O on a worker so painting and input stay responsive.

Configure HTTPS Verification

HTTPS verifies certificates and host names by default. TlsOptions is immutable; each configuration method returns a copy.

import klyn.net

tls = TlsOptions.clientDefault()
tls = tls.withCaFile("certificates/company-ca.pem")
tls = tls.withTlsVersions("1.2", "1.3")

client = HttpClient(timeout=5000u, tlsOptions=tls)
response = client.get("https://internal.example.com/health")

Mutual TLS is configured with withClientCertificate(certificatePath, privateKeyPath). The same trust concepts are available to low-level sockets through klyn.net.ssl.SSLContext.

Never disable verification in production

TlsOptions.insecure(), trustAll(), and their SSLContext equivalents are diagnostic escape hatches. They make interception undetectable and must not be used for deployed services.

Use Blocking TCP Sockets

Socket implements AutoClosable. Its text reader and writer facades are useful for line-oriented protocols, while sendBytes() and receiveBytes() preserve binary data.

import klyn.net

try socket = Socket("example.com", 80, 3000):
    socket.writeLine("GET / HTTP/1.1")
    socket.writeLine("Host: example.com")
    socket.writeLine("Connection: close")
    socket.writeLine("")
    print(socket.readAllText())

The constructor timeout controls connection establishment. Use setTimeoutMillis() to bound subsequent reads and writes.

Accept TCP Connections

ServerSocket(0) asks the operating system for a free port. accept() blocks until a client connects, so production servers normally accept on a dedicated thread and dispatch each connection deliberately.

import klyn.net

try server = ServerSocket(0):
    print("listening on " + server.localPort)

    try client = server.accept():
        line = client.readLine()
        client.writeLine("received: " + line)
Open a Low-Level TLS Socket
import klyn.net.ssl

context = SSLContext.clientDefault()
context = context.withTlsVersions("1.2", "1.3")

try socket = context.openSocket("example.com", 443):
    print(socket.protocol)
    print(socket.cipherSuite)

SSLSocket also supports upgrading an existing connected TCP socket. Certificate verification remains enabled unless the context explicitly disables it.

Handle Specific Network Failures
FailureException
Malformed or unsupported URL/protocolMalformedURLException or ProtocolException
Host resolutionUnknownHostException
Connection refusal/failureConnectException
Server bind failureBindException
Expired socket timeoutSocketTimeoutException
TLS negotiation or verificationSSLException

Catch the narrowest exception you can recover from. Let unexpected transport failures propagate with their original stack and source location instead of replacing them with a generic success value.