1- import usocket , os
1+ import usocket , os , time
22
33class Response :
44
@@ -7,13 +7,19 @@ def __init__(self, socket, saveToFile=None):
77 self ._saveToFile = saveToFile
88 self ._encoding = 'utf-8'
99 if saveToFile is not None :
10+ print ('Saving to file' , saveToFile )
11+ time .sleep (1 )
1012 CHUNK_SIZE = 512 # bytes
1113 with open (saveToFile , 'w' ) as outfile :
14+ print ('Opened file' , saveToFile )
15+ time .sleep (1 )
1216 data = self ._socket .read (CHUNK_SIZE )
1317 while data :
1418 outfile .write (data )
1519 data = self ._socket .read (CHUNK_SIZE )
1620 outfile .close ()
21+ print ('Data written to file' , saveToFile )
22+ time .sleep (1 )
1723
1824 self .close ()
1925
@@ -39,8 +45,14 @@ def text(self):
3945 return str (self .content , self ._encoding )
4046
4147 def json (self ):
42- import ujson
43- return ujson .loads (self .content )
48+ result = None
49+ try :
50+ import ujson
51+ result = ujson .load (self ._socket )
52+ finally :
53+ self .close ()
54+ return result
55+
4456
4557
4658class HttpClient :
@@ -49,6 +61,8 @@ def __init__(self, headers={}):
4961 self ._headers = headers
5062
5163 def request (self , method , url , data = None , json = None , file = None , custom = None , saveToFile = None , headers = {}, stream = None ):
64+ print ('Req' , url )
65+
5266 def _write_headers (sock , _headers ):
5367 for k in _headers :
5468 sock .write (b'{}: {}\r \n ' .format (k , _headers [k ]))
@@ -70,18 +84,34 @@ def _write_headers(sock, _headers):
7084 host , port = host .split (':' , 1 )
7185 port = int (port )
7286
87+ print ('Getting addr info' )
88+ time .sleep (1 )
7389 ai = usocket .getaddrinfo (host , port , 0 , usocket .SOCK_STREAM )
7490 if len (ai ) < 1 :
7591 raise ValueError ('You are not connected to the internet...' )
7692 ai = ai [0 ]
7793
78- print (ai )
79-
94+ print ('Opening socket' , ai )
95+ time . sleep ( 1 )
8096 s = usocket .socket (ai [0 ], ai [1 ], ai [2 ])
97+ print ('Socket open' )
98+ time .sleep (1 )
8199 try :
100+ print ('Connecting to socket' )
101+ time .sleep (1 )
82102 s .connect (ai [- 1 ])
103+ print ('Connected to socket' )
104+ time .sleep (1 )
83105 if proto == 'https:' :
84- s = ussl .wrap_socket (s , server_hostname = host )
106+ try :
107+ print ('Wrapping socket with ssl' )
108+ time .sleep (1 )
109+ s = ussl .wrap_socket (s )
110+ print ('Wrapped socket with ssl' )
111+ time .sleep (1 )
112+ except :
113+ print ("An error occurred." )
114+
85115 s .write (b'%s /%s HTTP/1.0\r \n ' % (method , path ))
86116 if not 'Host' in headers :
87117 s .write (b'Host: %s\r \n ' % host )
0 commit comments