2013-04-22 96 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){