@@ -199,7 +199,7 @@ def renewAccesTokenIfNeeded(self):
199199 "client_id" : self .clientID ,
200200 "client_secret" : self .clientSecret
201201 }
202- response = self .postRequest (self .authReq , postParams )
202+ response = self .postRequest (self .authReq , postParams , True )
203203 self .accessToken = self .params ['accessToken' ] = response ['access_token' ]
204204 self .refreshToken = self .params ['refreshToken' ] = response ['refresh_token' ]
205205 self .accessTokenExpiration = int (response ['expire_in' ]) + time .time ()
@@ -236,16 +236,36 @@ def getMeasure(self, moduleID, deviceID, measure):
236236 return None
237237
238238
239- def postRequest (self , url , params ):
239+ def postRequest (self , url , params , is_refresh_call = False ):
240240 params = urlencode (params )
241- headers = {"Content-Type" : "application/x-www-form-urlencoded;charset=utf-8" }
241+ headers = {
242+ "Content-Type" : "application/x-www-form-urlencoded;charset=utf-8"
243+ }
244+
245+ # Add the Authorization header if not a token refresh call and accessToken is available
246+ if not is_refresh_call and self .accessToken and self .accessToken .strip ():
247+ headers ["Authorization" ] = "Bearer {}" .format (self .accessToken )
248+ log .debug ("POST request to %s with params %s and headers %s" , url , params , headers )
242249 req = urllib2 .Request (url = url , data = params , headers = headers )
243250
244251 try :
245252 response = urllib2 .urlopen (req )
246253 return json .loads (response .read ())
254+ except urllib2 .HTTPError , e :
255+ # Log detailed error information
256+ log .error ("HTTPError: %s - %s" , e .code , e .reason )
257+ try :
258+ error_content = e .read ()
259+ log .error ("HTTPError Content: %s" , error_content )
260+ except Exception as read_error :
261+ log .error ("Unable to read HTTPError content: %s" , read_error )
262+ except urllib2 .URLError , e :
263+ log .error ("URLError: %s" , e .reason )
264+ except ValueError , e :
265+ log .error ("Invalid JSON response: %s" , e )
247266 except Exception , e :
248- log .exception (e )
267+ log .exception ("Unexpected error during request: %s" , e )
268+
249269 return None
250270
251271
0 commit comments