in libs/net/requests.ts [141:246]
function internalRequest(method: string, url: string, options?: RequestOptions): net.Response {
if (!options) options = {};
if (!options.headers) {
options.headers = {}
}
const tmp = pysplit(url, "/", 3)
let proto = tmp[0]
let host = tmp[2]
let path = tmp[3] || ""
// replace spaces in path
// TODO
// path = path.replace(" ", "%20")
let port = 0
if (proto == "http:") {
port = 80
} else if (proto == "https:") {
port = 443
} else {
control.fail("Unsupported protocol: " + proto)
}
if (host.indexOf(":") >= 0) {
const tmp = host.split(":")
host = tmp[0]
port = parseInt(tmp[1])
}
let sock: Socket;
if (proto == "https:") {
// for SSL we need to know the host name
sock = net.instance().createSocket(host, port, true)
} else {
sock = net.instance().createSocket(host, port, false)
}
// our response
let resp = new Response(sock)
// socket read timeout
sock.setTimeout(options.timeout)
sock.connect();
sock.send(`${method} /${path} HTTP/1.0\r\n`)
if (!options.headers["Host"])
sock.send(`Host: ${host}\r\n`)
if (!options.headers["User-Agent"])
sock.send("User-Agent: MakeCode ESP32\r\n")
// Iterate over keys to avoid tuple alloc
for (let k of Object.keys(options.headers))
sock.send(`${k}: ${options.headers[k]}\r\n`)
if (options.json != null) {
control.assert(options.data == null, 100)
options.data = JSON.stringify(options.json)
sock.send("Content-Type: application/json\r\n")
}
let dataBuf = dataAsBuffer(options.data)
if (dataBuf)
sock.send(`Content-Length: ${dataBuf.length}\r\n`)
sock.send("\r\n")
if (dataBuf)
sock.send(dataBuf)
let line = sock.readLine()
// print(line)
let line2 = pysplit(line, " ", 2)
let status = parseInt(line2[1])
let reason = ""
if (line2.length > 2) {
reason = line2[2]
}
while (true) {
line = sock.readLine()
if (!line || line == "\r\n") {
break
}
// print("**line: ", line)
const tmp = pysplit(line, ": ", 1)
let title = tmp[0]
let content = tmp[1]
if (title && content) {
resp.headers[title.toLowerCase()] = content.toLowerCase()
}
}
/*
elif line.startswith(b"Location:") and not 200 <= status <= 299:
raise NotImplementedError("Redirects not yet supported")
*/
if ((resp.headers["transfer-encoding"] || "").indexOf("chunked") >= 0)
control.fail("not supported chunked encoding")
resp.status_code = status
resp.reason = reason
return resp
}