@@ -25,22 +25,25 @@ def request(url):
25
25
port = int (port )
26
26
27
27
# 4. Connect
28
- with socket .socket (socket .AF_INET , socket .SOCK_STREAM , socket .IPPROTO_TCP ) as s :
28
+ with socket .socket (socket .AF_INET , socket .SOCK_STREAM , socket .IPPROTO_TCP ) as sock :
29
29
if scheme == "https" :
30
30
ctx = ssl .create_default_context ()
31
- s = ctx .wrap_socket (s , server_hostname = host )
31
+ with ctx .wrap_socket (sock , server_hostname = host ) as ssock :
32
+ return _get_headers_and_body (ssock , host , port , path )
33
+ return _get_headers_and_body (sock , host , port , path )
32
34
33
- s .connect ((host , port ))
34
35
35
- # 5. Send request
36
- s .send (f"GET { path } HTTP/1.0\r \n " .encode ())
37
- s .send (f"Host: { host } \r \n " .encode ())
38
- s .send ("Accept-Encoding: br,gzip,deflate\r \n " .encode ())
39
- s .send ("\r \n " .encode ())
36
+ def _get_headers_and_body (sock , host , port , path ):
37
+ sock .connect ((host , port ))
40
38
41
- # 6. Receive response
42
- response = s .makefile ("rb" , newline = "\r \n " )
39
+ # 5. Send request
40
+ sock .send (f"GET { path } HTTP/1.0\r \n " .encode ())
41
+ sock .send (f"Host: { host } \r \n " .encode ())
42
+ sock .send ("Accept-Encoding: br,gzip,deflate\r \n " .encode ())
43
+ sock .send ("\r \n " .encode ())
43
44
45
+ # 6. Receive response
46
+ with sock .makefile ("rb" , newline = "\r \n " ) as response :
44
47
# 7. Read status line
45
48
line = response .readline ().decode ()
46
49
# 8. Parse status line
@@ -55,15 +58,16 @@ def request(url):
55
58
line = response .readline ().decode ()
56
59
if line == "\r \n " :
57
60
break
61
+
58
62
header , value = line .split (":" , 1 )
59
63
headers [header .lower ()] = value .strip ()
60
64
61
65
body = response .read ()
62
66
if "content-encoding" in headers :
63
67
encoding = headers ["content-encoding" ]
64
68
body = decompress (body , encoding )
65
- body = body .decode ()
66
69
70
+ body = body .decode ()
67
71
# 12. Return
68
72
return headers , body
69
73
0 commit comments