2013-04-22 94 views
1

我們正在創建一個小型項目,在該項目中我們將瓶子作爲基於Web前端和Restlet的WebService。POST請求中的JSON不受支持Restlet

我們試圖從燒瓶發送登錄數據作爲JSON來的Restlet:

def login(): 
    error = None 
    if request.method == 'POST': 
     payload = {'username' : request.form['username'], 'password' : request.form['password']} 
     headers = {'Content-Type': 'application/json'} 
     req = requests.post(WEBSERVICE_IP + '/login', data=json.dumps(payload), headers=headers) 
     (...) 

瓶基於網站叫喊:

ValueError: No JSON object could be decoded 

我們不知道如何瓶之間協調溝通的Restlet。

編輯(22-04下午10:08 GMT): 我發現,性反應是:

<html> 
(...) 
Unsupported Media Type 
The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method 
(...) 
</html> 

編輯(22-04下午11時26分GMT): 我仍然不知道爲什麼,但我認爲它可能是JSON格式的東西。糾正我的代碼後,它會發送正確的JSON(稱爲JSONLint),我仍然得到相同的消息。任何人都知道如何在Python中創建JSONObject? WebService的方法有:

@Post("json") 
public JSONObject verifyAccount(JSONObject dane){ 

編輯(23-04下午7時26 GMT): 確定。所以我們幾乎可以確定這是隱形標題的問題。任何人都可以確認在Python代碼中創建頭文件是正確的嗎?

編輯(24-04 5:40 PM GMT): 問題仍然存在。正如其他人所建議的,我將請求更改回urllib2。這有助於第一件事 - 「價值問題」。現在,瀏覽器現在有

urllib2.HTTPError 
HTTPError: HTTP Error 415: Unsupported Media Type 

POST請求:

@app.route('/login', methods=['GET', 'POST']) 
def login(): 
    error = None 
    if request.method == 'POST': 
     payload = {"Login": request.form['username'], 
      "Haslo": request.form['haslo']} 
     data = json.dumps(payload) 
     clen = len(data) 
     req = urllib2.Request(WEBSERVICE_IP + '/login', data, 
      {'Content-Type': 'application/json', 'Content-Length': clen}) 
     f = urllib2.urlopen(req) 
     response = f.read() 
     f.close() 

編輯(24-04 18:20 GMT)

Wireshark captured POST request and it looks ok.

Wireshark的捕獲POST請求,並將其看起來不錯。

回答

2

好的。解決方案比我想象的要容易。

問題出現在WebService端。它是通過改變的JSONObject到JsonRepresentation解決:

@Post("json") 
public JSONObject verifyAccount(JsonRepresentation data){ 
2

如果data是字典,請求將序列化它。你想傳遞一個字符串代替:

import json 

req = requests.post(WEBSERVICE_IP + '/login', data=json.dumps(payload), ... 
+0

謝謝,改變了這一切,但仍是同樣的問題。 – Hazardius 2013-04-24 18:35:33

1

除了Blender的點(這是一個更可能是罪魁禍首),值得一提的是,內容類型應被設置爲application/json,而不是json

+0

好吧,但我們只是嘗試了所有可能的組合:「json」,「application/json」,什麼都沒有。 仍然沒有連接。 – Hazardius 2013-04-24 18:36:23

1

要在危險的迴應,我不得不編輯@Post("json")@Post("application/json")

@Post("application/json") 
public JSONObject verifyAccount(JsonRepresentation data){