But when I try to fetch the css file, it just hangs on response.read
Assistant
User
But I have this code:
code
if "content-length" in response_headers:
content = response.read(int(response_headers["content-length"]))
else:
content = response.read()
Yet it enters the else clause. Also, transfer-encoding is not present in the headers.
Assistant
User
I now have:
code
elif "transfer-encoding" in response_headers:
while True:
chunk_size_line = response.readline()
chunk_size = int(chunk_size_line, 16)
if chunk_size == 0:
break
chunk = response.read(chunk_size)
content += chunk
response.readline()
and I get
content += chunk
TypeError: can only concatenate str (not "bytes") to str
Assistant
User
But why does it work with the html file? That's bytes as well, right?
Assistant
User
No, I open the socket like this in both cases: response = sock.makefile("rb", encoding="utf8", newline="\r\n")
Assistant
The reason response.read() hangs when fetching a CSS file (but not an HTML page) is typically because .read() tries to read until EOF (end-of-file), but the server doesn't close the connection after sending the CSS content, so your read call blocks waiting for more data that never arrives.
This is common behavior for HTTP/1.1 persistent connections (keep-alive), where the server keeps the connection open after sending the response — especially for static assets like CSS, JS, or images.
How to fix it: Properly parse the HTTP response instead of just calling .read() blindly
You need to:
Read exactly as many bytes as the response's Content-Length header indicates, or
If the Transfer-Encoding is chunked, read and decode the chunked response.
What happens in your code
Your code currently does:
python
response = sock.makefile("rb", encoding="utf8", newline="\r\n")
content = response.read() # Reads until EOF, but connection remains open → hangs
To fix this you should:
Read the response headers line-by-line until the blank line that separates headers from the body.
Parse headers to find the Content-Length or check for Transfer-Encoding: chunked.
Read exactly the indicated amount of body data, or decode chunked data.
Rough example of how you can do it
python
def read_response(sock):
response = sock.makefile("rb", encoding="utf8", newline="\r\n")
# 1. Read status line
status_line = response.readline()
print(f"Status line: {status_line.strip()}")
# 2. Read headers
headers = {}
while True:
line = response.readline()
if line == "\r\n" or line == "\n" or line == "":
break
key, value = line.split(":", 1)
headers[key.strip().lower()] = value.strip()
print("Headers:", headers)
# 3. Read body based on headers info
body = b""
if "content-length" in headers:
length = int(headers["content-length"])
body = response.read(length)
elif headers.get("transfer-encoding") == "chunked":
# Need to parse chunked transfer encoding
while True:
chunk_size_line = response.readline()
chunk_size = int(chunk_size_line.strip(), 16)
if chunk_size == 0:
break
chunk = response.read(chunk_size)
body += chunk
# Read the trailing \r\n after chunk
response.readline()
else:
# No Content-Length or chunked encoding — fallback read until connection close
# But this may hang if the server keeps connection alive
body = response.read()
return status_line, headers, body
# Usage
status, headers, content = read_response(sock)
print(content) # your CSS or HTML content
Summary:
Never just blindly call .read() on HTTP socket file-like after sending a request.
Always parse the HTTP response headers first, extract content length or transfer encoding info then read the body accordingly.
For CSS files fetched over HTTP/1.1 with persistent connection, the server typically keeps the connection alive after sending the response body, so .read() blocks waiting for EOF that never comes.
Parsing the headers to find Content-Length (almost always sent for CSS files) and reading exactly that many bytes solves the hang.
If you want, I can help you build a complete minimal HTTP response reader!
Thanks for that info! If your code reads headers and then checks
python
if "content-length" in response_headers:
content = response.read(int(response_headers["content-length"]))
else:
content = response.read()
but still falls into the else (no Content-Length) case and hangs, here are some possibilities to troubleshoot:
1. Is your header parsing correct and case-insensitive?
HTTP headers are case-insensitive by spec. You must be sure your response_headers dict keys are all lowercased.
Example: if the server sends Content-Length: 1234, your dict key should be "content-length" (lowercase).
Make sure your code lowercases header names when parsing, e.g.:
python
key, value = line.split(":", 1)
response_headers[key.strip().lower()] = value.strip()
If you do that and then check "content-length" key, it should be found.
If your dict keys are like "Content-Length" but you check lowercase, or vice versa, the check will fail.
2. Is the server perhaps omitting Content-Length for that response?
Sometimes servers:
Use Transfer-Encoding: chunked (you said it's not present).
Close the connection to delimit the end of response body (HTTP/1.0 style). But you're using HTTP/1.1 by default, so keep-alive is implied unless stated otherwise.
Send a response like status 304 Not Modified without body and no content-length.
Use a response with no body (e.g. HEAD responses, or 204 No Content).
Double-check the full headers for the CSS request. Add a printout of all raw headers you got:
python
print(repr(headers))
3. Are you waiting to read response headers completely before you start reading the body?
If you miss the empty line that separates headers from the body or if you call read() too early, your response reading may get desynchronized.
Make sure your code:
Reads the status line.
Reads headers line by line until it encounters a blank line (only \r\n).
Then, once you get the content-length, switch to reading bytes for the body, or alternatively open a second file handle with "rb" mode. Mixing modes on the same file can cause trouble.
Or, read everything as bytes, then decode headers yourself.
Example using bytes:
python
response = sock.makefile("rb")
# read status line in bytes, decode with utf-8
status_line = response.readline().decode('utf-8').strip()
headers = {}
while True:
line = response.readline().decode('utf-8')
if line == '\r\n' or line == '\n' or line == '':
break
key, value = line.split(':', 1)
headers[key.lower().strip()] = value.strip()
content_length = int(headers.get("content-length", 0))
content = response.read(content_length)
5. Make sure you print what headers you actually got
Add print or logging after header parsing:
python
print("Response headers:")
for k, v in headers.items():
print(f"{k}: {v}")
This will confirm if content-length is actually sent or not.
6. If no Content-Length and no Transfer-Encoding header, server might be closing connection after sending response
In that case, reading until socket EOF (connection close) is necessary.
But sometimes servers keep connection alive and send no content length. Then you're stuck.
You can:
Use HTTP/1.0 in request to force connection close (add Connection: close header).
Or parse until EOF.
Practical tip: Send Connection: close in your request headers for now
Add this header in your HTTP request, e.g.:
code
GET /style.css HTTP/1.1
Host: example.com
Connection: close
This will tell the server to close the connection when done.
Then the socket EOF signals end of body, so calling response.read() works.
If you do that, then response.read() can safely read all remaining bytes and return.
In summary:
Fix makefile mode and encoding mismatch.
Ensure headers parsed with lowercased keys.
Print headers to verify what you received.
If missing content-length and no chunked encoding, use Connection: close header to allow reading until EOF.
Then read the body accordingly.
If you want, I can help you rewrite your fetch code to do all these robustly; just ask!
The error message:
code
TypeError: can only concatenate str (not "bytes") to str
means you're trying to add a bytes object (chunk returned by response.read(chunk_size)) to a string (content) — Python doesn't allow mixing these types.
Why is this happening?
Your response is a file-like object opened with encoding="utf8" (i.e. text mode) but you're calling response.read(chunk_size). The behavior of response.read(n) in text mode is to return a string, not bytes.
But you see the error says that chunk is bytes, so probably your response object is opened in binary mode ("rb"), so read() returns bytes.
Meanwhile, your content variable was probably initialized as a string:
python
content = ""
Adding bytes to a string causes the error.
How to fix it:
You have two options:
Work with bytes everywhere:
Initialize content as a bytes object: content = b""
Read in binary mode ("rb")
Process bytes and decode only after full body is read.
Work with strings everywhere:
Open response in text mode ("r", with encoding="utf8")
Read chunks as strings (using read(chunk_size) in text mode)
Initialize content = ""
Which one to pick?
HTTP body is just bytes: can be any binary file (CSS, images, scripts, HTML, etc.). So the safest way is to read bytes and decode to string only if you expect text (HTML, CSS) or you want to handle bytes as bytes (e.g. for images).
So fix 1 (recommended):
python
# Make sure socket file is opened in binary mode, no encoding:
response = sock.makefile("rb") # no encoding
content = b"" # bytes
if "transfer-encoding" in response_headers:
while True:
chunk_size_line = response.readline()
chunk_size = int(chunk_size_line.strip(), 16)
if chunk_size == 0:
break
chunk = response.read(chunk_size)
content += chunk
# Remove trailing \r\n after chunk data
response.readline()
# At this point content is bytes.
# Decode to string if you know it's utf-8 text, e.g.
text_content = content.decode("utf-8")
If you do want to process everything as strings, open response in text mode, but then handling chunks is tricky because chunk sizes are byte counts, but in text mode .read(n) reads characters, and due to variable byte-length for utf8 characters, reading exact byte count is unreliable. So for chunked encoding reading, it's much better to work in bytes mode.
Also:
Be sure to .strip() chunk size line, as it usually ends with \r\n
python
chunk_size = int(chunk_size_line.strip(), 16)
Recap:
For HTTP chunked transfer encoding, always read in binary mode.
Initialize content = b"" (bytes).
At the end, decode as needed.
Don't mix str and bytes in += operations.
If you want, I can provide a full snippet example of reading chunked HTTP response.
Great question!
Why does reading the HTML response work but CSS chunked response complains about mixing str and bytes?
The key lies in how you open the socket file (makefile) and how you read the response in each case:
When fetching the HTML page:
You probably open the socket file in text mode, like this:
Here, .read() and .readline() return strings, and content should be a string.
Binary mode:
python
response = sock.makefile("rb")
Here, .read() and .readline() return bytes, and content should be bytes (b"").
For chunked Transfer-Encoding
You must use binary mode ("rb") because chunk sizes and chunk data lengths are in bytes.
Reading chunk sizes as strings (readline() with decoding) is okay, but actual chunk data reading must be byte-exact.
So for chunks:
python
response = sock.makefile("rb")
content = b""
# read status line (bytes), decode as utf8 with .decode() as needed
status_line = response.readline().decode("utf8").strip()
# read headers, decode each line from bytes to str
headers = {}
while True:
line = response.readline().decode("utf8")
if line in ("\r\n", "\n", ""):
break
key, val = line.split(":",1)
headers[key.strip().lower()] = val.strip()
# Now read body (chunked or via content-length)
if headers.get("transfer-encoding") == "chunked":
while True:
chunk_size_line = response.readline().decode("utf8")
chunk_size = int(chunk_size_line.strip(), 16)
if chunk_size == 0:
break
chunk = response.read(chunk_size)
content += chunk
response.readline() # consume trailing \r\n
else:
# handle content-length or connection close
pass
# After all, decode content if needed
decoded_content = content.decode("utf8")
Summary
Don't open with "rb" and encoding simultaneously.
For simple text response without chunked encoding, "r" + encoding="utf8" is fine.
For chunked responses, always read binary bytes with "rb" and decode headers manually.
If you fix the makefile() mode usage as above, your .read() and concatenation issues should go away.