Sign in

HTTP vs. HTTPS Explained: From Plain Text Requests to TLS Encryption

Learn how HTTP coordinates client-server communication and how HTTPS secures it with cryptographic handshakes, certificates, and symmetric encryption.

MonksBit Desk

November 25, 2026 · 9 min read · 17 views

Read

Hypertext Transfer Protocol (HTTP) is an application-layer network protocol used to transmit structured documents and messages between a client and a server. Hypertext Transfer Protocol Secure (HTTPS) extends HTTP by tunneling its communication through Transport Layer Security (TLS), providing confidentiality, data integrity, and endpoint authentication.

You will need. Basic knowledge of client-server network architecture · Familiarity with socket programming or network request basics

How well do you know this already?

The full lesson

Level 1 · Beginner: The request-response cycle and message format

The web relies on a simple conversational pattern known as the request-response cycle. A client, such as a web browser, opens a network connection to a server and sends an HTTP request. The server parses the request, executes relevant business logic, and returns an HTTP response before potentially closing or reusing the connection.

An HTTP message is structured text. A request begins with a start line containing an HTTP method such as GET or POST, the target resource path, and the protocol version. Below the start line are headers, which are key-value pairs providing metadata such as hostnames and accepted formats. An empty line separates the headers from an optional message body containing data payloads.

Consider fetching an index document from a server. The client sends a GET line, specifies the Host header, and marks the end of headers with a blank line. The server replies with a status line indicating success, headers describing payload size and media type, a blank line, and the raw document body.

A minimal HTTP/1.1 client sending a raw GET request over a TCP socket

import socketdef fetch_simple_http(host: str, port: int = 80) -> str:    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    client_socket.connect((host, port))        request = (        f"GET / HTTP/1.1\r\n"        f"Host: {host}\r\n"        f"Connection: close\r\n"        f"\r\n"    )    client_socket.sendall(request.encode('utf-8'))        response_chunks = []    while True:        data = client_socket.recv(4096)        if not data:            break        response_chunks.append(data)            client_socket.close()    return b"".join(response_chunks).decode('utf-8', errors='replace')if __name__ == "__main__":    print(fetch_simple_http("example.com"))

Key takeaways

  • HTTP is a request-response protocol running on top of reliable transport like TCP.
  • Messages consist of a start line, key-value headers, an empty line delimiter, and an optional body.
  • Raw HTTP transmits data as unencrypted plain text across the network.

Level 2 · Intermediate: Securing the transport layer with TLS

Plain HTTP leaves communication vulnerable to eavesdropping, packet alteration, and machine impersonation. HTTPS resolves these threats by inserting the Transport Layer Security (TLS) protocol directly between the transport layer (TCP) and application layer (HTTP). Rather than sending raw text across the TCP socket, the client and server negotiate encryption keys first.

The security handshake begins with the client sending a ClientHello message detailing supported cipher suites and a random nonce. The server replies with a ServerHello, selecting the cipher suite, providing its own random nonce, and presenting its X.509 digital certificate. The client verifies this certificate against a local trust store of root Certificate Authorities (CAs). If valid, both parties perform an asymmetric key exchange (such as Ephemeral Diffie-Hellman) to compute shared symmetric session keys without ever transmitting the secret key across the wire.

Once session keys are established, all subsequent HTTP start lines, headers, and bodies are encrypted using authenticated symmetric ciphers such as AES-GCM or ChaCha20-Poly1305. To handle errors, clients must catch certificate verification failures and connection drops before processing application payloads.

We can verify HTTPS connections programmatically using standard network libraries that wrap native operating system TLS implementations to enforce certificate validation.

Establishing a secure HTTPS connection with explicit certificate verification

import socketimport ssldef fetch_secure_https(host: str, port: int = 443) -> str:    context = ssl.create_default_context()    context.check_hostname = True    context.verify_mode = ssl.CERT_REQUIRED    raw_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    raw_socket.settimeout(10.0)        with context.wrap_socket(raw_socket, server_hostname=host) as secure_socket:        secure_socket.connect((host, port))        request = (            f"GET / HTTP/1.1\r\n"            f"Host: {host}\r\n"            f"User-Agent: MonksBitClient/1.0\r\n"            f"Connection: close\r\n"            f"\r\n"        )        secure_socket.sendall(request.encode('utf-8'))                chunks = []        while True:            chunk = secure_socket.recv(4096)            if not chunk:                break            chunks.append(chunk)                return b"".join(chunks).decode('utf-8', errors='replace')if __name__ == "__main__":    response = fetch_secure_https("example.com")    status_line = response.split('\r\n')[0]    print(f"Response Status: {status_line}")

Key takeaways

  • HTTPS establishes a secure TLS tunnel before any HTTP headers or bodies are sent.
  • Authentication relies on public key certificates signed by trusted Certificate Authorities.
  • Asymmetric encryption is used solely to establish identity and negotiate fast symmetric session keys.

Level 3 · Advanced: Protocol evolution, performance optimizations, and modern architectures

HTTP/1.1 introduced persistent TCP connections using the Keep-Alive header, avoiding the overhead of establishing a new three-way handshake for every file. However, HTTP/1.1 suffers from Head-of-Line (HoL) blocking at the application level: requests on a single connection must be answered in strict sequential order. If an early request encounters slow database processing, subsequent responses must wait.

HTTP/2 resolved application-level HoL blocking by replacing plain text streams with binary framing. It multiplexes multiple logical streams over a single TCP connection, introduces HPACK header compression, and allows server push. Despite this, HTTP/2 remains vulnerable to transport-level HoL blocking: if a single TCP packet is dropped at the IP layer, TCP halts delivery of all multiplexed streams until the missing segment is retransmitted.

HTTP/3 overcomes transport HoL blocking by migrating from TCP to QUIC, an encrypted transport protocol built on top of UDP. QUIC handles stream multiplexing and retransmission independently per stream, incorporates TLS 1.3 handshakes into the initial connection phase to achieve 0-RTT connection resumptions, and prevents network handoff stalls using connection identifiers instead of IP-port tuples.

In distributed system design, decrypting TLS directly on application servers wastes substantial CPU resources. Modern architectures terminate HTTPS at reverse proxies, load balancers, or edge content delivery networks (CDNs). The edge proxy handles TLS handshakes and certificate rotations, forwarding traffic across a protected private network to backend microservices via internal HTTP or gRPC.

A multithreaded HTTP/1.1 reverse proxy demonstrating TLS termination

import socketimport sslimport threadingdef pipe(source: socket.socket, destination: socket.socket) -> None:    try:        while True:            data = source.recv(8192)            if not data:                break            destination.sendall(data)    except OSError:        pass    finally:        source.close()        destination.close()def handle_client(client_sock: socket.socket, backend_host: str, backend_port: int) -> None:    try:        backend_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        backend_sock.connect((backend_host, backend_port))    except OSError:        client_sock.close()        return    t1 = threading.Thread(target=pipe, args=(client_sock, backend_sock))    t2 = threading.Thread(target=pipe, args=(backend_sock, client_sock))    t1.start()    t2.start()def run_tls_termination_proxy(listen_port: int, certfile: str, keyfile: str, backend_host: str, backend_port: int) -> None:    context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)    context.load_cert_chain(certfile=certfile, keyfile=keyfile)    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)    server_sock.bind(("0.0.0.0", listen_port))    server_sock.listen(128)    while True:        raw_client, _ = server_sock.accept()        try:            tls_client = context.wrap_socket(raw_client, server_side=True)            worker = threading.Thread(target=handle_client, args=(tls_client, backend_host, backend_port))            worker.daemon = True            worker.start()        except ssl.SSLError:            raw_client.close()

Key takeaways

  • HTTP/2 uses binary framing and multiplexing to prevent application-level head-of-line blocking.
  • HTTP/3 replaces TCP with QUIC over UDP to eliminate transport-level packet stall bottlenecks.
  • Edge TLS termination isolates cryptographic CPU overhead to perimeter proxies while preserving backend service throughput.

Complexity

  • Time: Best case: O(1) round trips for resumed connections. Worst case: O(N) round trips during initial TCP and TLS handshakes, plus O(M) time to transfer M bytes.
  • Space: O(B) auxiliary space, where B is the buffer size required to store headers, decrypt TLS records, and assemble frames.

Initial HTTP/1.1 and TLS 1.2 setups take up to three network round trips (TCP SYN/ACK plus TLS negotiation) before application data flows. TLS 1.3 reduces this to a single round trip, while HTTP/3 over QUIC can establish secure transport in a single combined round trip or zero round trips when resuming previous sessions. Memory complexity corresponds to socket receive buffers and maximum TLS record frame sizes (typically up to 16 kilobytes per record).

Common mistakes

  • Disabling certificate validation (such as setting verify=False in network clients) to bypass self-signed certificate errors during testing, leaving production environments open to man-in-the-middle attacks.
  • Assuming HTTPS hides the domain name or IP destination; network observers can still inspect DNS queries, target IP addresses, and Server Name Indication (SNI) extensions unless Encrypted Client Hello (ECH) is deployed.
  • Failing to implement HTTP Strict Transport Security (HSTS), which allows initial unencrypted HTTP requests to be intercepted before being redirected to HTTPS.
  • Treating HTTP/1.1 connections as single-use by closing them after every request instead of utilizing persistent connection pooling, incurring redundant TCP and TLS handshake overhead.

Practice problems

  1. Parse HTTP status codes and headers (easy). Hint: Read from the socket line-by-line until encountering a carriage-return newline delimiter, splitting status tokens by single spaces.
  2. Implement an HTTP redirect handler (medium). Hint: Inspect 3xx status codes, extract the Location header target, update your socket destination, and preserve loop counters to prevent infinite cycles.
  3. Build a multiplexed frame parser for HTTP/2 (hard). Hint: Read fixed 9-byte header prefixes to determine length, frame type, flags, and stream identifier before consuming the variable-length frame payload.

Summary

HTTP standardizes client-server messaging through clean request-response structures, while HTTPS wraps those messages in cryptographic tunnels managed by TLS. Over decades of performance optimization, the protocol evolved from sequential plain text over single TCP sockets (HTTP/1.1) to multiplexed binary streams (HTTP/2) and independent stream transport over QUIC (HTTP/3), maintaining consistent application semantics while minimizing latency and security vulnerabilities.

Finish the Prove step above to complete this lesson.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!