kopia lustrzana https://github.com/pimoroni/pimoroni-pico
PicoWireless: handle encoding/content type better in ppwhttp
Uses the correct? default Content-Type and encoding for HTTP. Parses the Content-Type header *before* decoding the content body. Handles JSON type gracefully. Decodes the response body accoding to the encoding header.pull/208/head
rodzic
eb3c8b0ebc
commit
b92d77a2f9
|
@ -149,23 +149,33 @@ Connection: close
|
||||||
data = picowireless.get_data_buf(client_sock)
|
data = picowireless.get_data_buf(client_sock)
|
||||||
response += data
|
response += data
|
||||||
|
|
||||||
response = response.decode("utf-8")
|
head, body = response.split(b"\r\n\r\n", 1)
|
||||||
|
head = head.decode("utf-8")
|
||||||
head, body = response.split("\r\n\r\n", 1)
|
|
||||||
dhead = {}
|
dhead = {}
|
||||||
|
|
||||||
for line in head.split("\r\n")[1:]:
|
for line in head.split("\r\n")[1:]:
|
||||||
key, value = line.split(": ", 1)
|
key, value = line.split(": ", 1)
|
||||||
dhead[key] = value
|
dhead[key] = value
|
||||||
|
|
||||||
# Fudge to handle JSON data type, which is prefixed with a content length.
|
encoding = "iso-8869-1"
|
||||||
# This ignores the charset, if specified, since we've already assumed utf-8 above!
|
content_type = "application/octet-stream"
|
||||||
# TODO maybe pay attention to Content-Type charset
|
|
||||||
if "Content-Type" in dhead and dhead["Content-Type"].startswith("application/json"):
|
if "Content-Type" in dhead:
|
||||||
length, body = body.split("\n", 1)
|
ctype = dhead["Content-Type"].split("; ")
|
||||||
|
content_type = ctype[0].lower()
|
||||||
|
for c in ctype:
|
||||||
|
if c.startswith("encoding="):
|
||||||
|
encoding = c[9:]
|
||||||
|
|
||||||
|
# Handle JSON content type, this is prefixed with a length
|
||||||
|
# which we'll parse and use to truncate the body
|
||||||
|
if content_type == "application/json":
|
||||||
|
length, body = body.split(b"\r\n", 1)
|
||||||
length = int(length, 16)
|
length = int(length, 16)
|
||||||
body = body[:length]
|
body = body[:length]
|
||||||
|
|
||||||
|
body = body.decode(encoding)
|
||||||
|
|
||||||
handler(dhead, body)
|
handler(dhead, body)
|
||||||
|
|
||||||
picowireless.client_stop(client_sock)
|
picowireless.client_stop(client_sock)
|
||||||
|
|
Ładowanie…
Reference in New Issue