What's needed for a browser, Safari and Opera in particular to understand an HTTP response?

http, httpresponse, python

Solution

You state that you are sending a literal string like:

'''
HTTP/1.1 200 OK\r\n
<!DOCTYPE html>
...
'''

However, Python only adds a single `\n` corresponding to a newline in a triple-quoted string. So the bytes that are sent end up being

HTTP/1.1 200 OK\r\n\n<!DOCTYPE html>...

As you can see, there is a missing `\r`. I suggest you use code like the following:

sock.send("HTTP/1.1 200 OK\r\n\r\n")

In the above, you may want to add a `Content-type` header:

sock.send("HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n")

Then, after sending the header, send the document payload:

sock.send('''
<!DOCTYPE html>
...
''')

This separates the protocol-level header from the data payload, and makes your code easier to understand. It's also easier to get the `\r\n` right in the header, since that's where it matters.

Problem

I have an HTTP response of ``` HTTP/1.0 200 OK\r\n\r\n <!DOCTYPE html>... ``` Both Firefox and Chrome seem to understand it just fine and show the HTML content - however Safari and Opera just show me everything in plaintext. Adding a "Content-Type" field messes everything up for all browsers. What's the catch? I am not going to post the full code because there is a lot of arbitrary programming logic not related to the issue, however, what happens is something like this: I create a socket, then all the related socket operations occur - all this works like magic, then after all the processing I .send(' response here ') and for some reason it only shows on Firefox and Chrome. The response string looks like this: ``` ''' HTTP/1.1 200 OK\r\n <!DOCTYPE html> ... ... </html> ''' ``` This is what I am seeing: http://cl.ly/0y0U1s0G3X2v1C11282S

Original source