user2555349 user2555349 - 3 months ago 9
HTTP Question

Python - Reading HTTP Request Body

I am trying to send data to my Python server using HTTP.

My JavaScript code:

xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", url, true);
xmlHttp.send(String.fromCharCode(0xf5));


My Python code:

#sock is a socket object
header = readline(sock)
contl = 0
while(len(header) > 0):
header = readline(sock)
dat = header.split(': ')
if(len(dat) >= 2):
if(dat[0] == 'Content-Length'):
contl = int(float(dat[1]))
print sock.recv(contl)


readline function:

def readLine(sock):
s = ""
while(True):
a = sock.recv(1)
if(len(a) < 1):
return s
elif(a == '\n'):
return s
elif(a == '\r'):
b = sock.recv(1)
if(b == '\n'):
return s
else:
s += a + b
else:
s += a


Instead of my Python code printing
\xf5
it prints
\xc3\xb5
. Is there something I'm missing?

Answer

\xc3\xb5 is UTF-8 representation of U+00F5

>>> u'\xf5'.encode('utf-8')
'\xc3\xb5'

You can covert it back using str.decode (bytes.decode in Python 3.x):

>>> b'\xc3\xb5'.decode('utf-8')
u'\xf5'