@@ -14,18 +14,37 @@ class ProtocolError(Exception):
14
14
15
15
16
16
async def get_json (url ):
17
+ return await _request_json ("GET" , url )
18
+
19
+
20
+ async def post_form (url , params ):
21
+ content_type = "application/x-www-form-urlencoded"
22
+ body = urllib .parse .urlencode (params ).encode ()
23
+ return await _request_json ("POST" , url , content_type , body )
24
+
25
+
26
+ async def _request_json (method , url , content_type = None , body = None ):
17
27
url = urllib .parse .urlsplit (url )
18
28
headers = [
19
29
("Host" , url .netloc ),
20
30
("User-Agent" , h11 .PRODUCT_ID ),
21
31
("Accept" , "application/json" ),
22
32
("Connection" , "close" ),
23
33
]
34
+ if body is not None :
35
+ headers += [
36
+ ("Content-Type" , content_type ),
37
+ ("Content-Length" , str (len (body ))),
38
+ ]
24
39
25
40
conn = h11 .Connection (our_role = h11 .CLIENT )
41
+
26
42
to_send = conn .send (
27
- h11 .Request (method = "GET" , target = url .path or "/" , headers = headers )
43
+ h11 .Request (method = method , target = url .path or "/" , headers = headers )
28
44
)
45
+ if body is not None :
46
+ to_send += conn .send (h11 .Data (body ))
47
+ to_send += conn .send (h11 .EndOfMessage ())
29
48
30
49
if url .scheme == "https" :
31
50
default_port = 443
@@ -40,7 +59,6 @@ async def get_json(url):
40
59
41
60
async with util .connect (url .hostname , port , ssl = ssl ) as (reader , writer ):
42
61
writer .write (to_send )
43
- writer .write (conn .send (h11 .EndOfMessage ()))
44
62
await writer .drain ()
45
63
46
64
async def receive_all ():
0 commit comments