2017-02-18 78 views
0

我想用下面的代码连接到一个REST API:的Python连接到REST API

data = requests.get("http://pbx/rest/login").json() 
head = {'loginType' : 'Internal','nonce' : data["nonce"], 'secret' : (hashlib.sha1((LOGIN_ID+data['nonce']+PASSWORD).encode('utf-8')).hexdigest())} 
data_new = requests.post('http://pbx/rest/login',data=head) 
print(data_new) 

请求随机数从PBX只是正常工作,那么我需要生成登录秘密,有权发布它的PBX和答案应该是一个令牌

但打印(data_new)强制显示我和打印(data_new.json()),并出现以下错误崩溃:

Traceback (most recent call last): 
    File "starface.py", line 14, in <module> 
    Connect() 
    File "starface.py", line 12, in Connect 
    data_new = requests.post(SERVER+"login",data=head).json() 
    File "C:\Users\BüroNotebook\AppData\Local\Programs\Python\Python35-32\lib\site 
-packages\requests\models.py", line 866, in json 
    return complexjson.loads(self.text, **kwargs) 
    File "C:\Users\BüroNotebook\AppData\Local\Programs\Python\Python35-32\lib\json 
\__init__.py", line 319, in loads 
    return _default_decoder.decode(s) 
    File "C:\Users\BüroNotebook\AppData\Local\Programs\Python\Python35-32\lib\json 
\decoder.py", line 339, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "C:\Users\BüroNotebook\AppData\Local\Programs\Python\Python35-32\lib\json 
\decoder.py", line 357, in raw_decode 
    raise JSONDecodeError("Expecting value", s, err.value) from None 
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 

回答

1

看起来你得到一个空白的响应体,没有什么可以解析的。这里有一个片段,以获得相同的JSON错误:

>>> import json 
>>> json.loads('') 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python3.4/json/__init__.py", line 318, in loads 
    return _default_decoder.decode(s) 
    File "/usr/lib/python3.4/json/decoder.py", line 343, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "/usr/lib/python3.4/json/decoder.py", line 361, in raw_decode 
    raise ValueError(errmsg("Expecting value", s, err.value)) from None 
ValueError: Expecting value: line 1 column 1 (char 0) 

所以我会做到以下几点:

  1. print(d.headers, d.status_code)。你会看到你的HTTP响应代码,并可能在响应头文件中有帮助。考虑到这些信息,请检查您的pbx服务器的文档以找出它的含义,然后可以按照您提出第二个请求的方式修复某些内容。
  2. 如果您有权访问日志文件,请检查那里发生了什么。如果你没有这种访问接触到有人谁