我正在开发一个 Android 应用程序,在该应用程序中,我必须在使用 Cherrypy 构建的 REST API 上发出 POST HTTP 请求。
这是应用程序的java代码:
public String post(String host,int port,String path,String msg) throws IOException{
URL url = new URL ("http",host,port,path);
Log.e("track","sto per connettermi");
URLConnection conn = url.openConnection();
Log.e("track","connesso");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setAllowUserInteraction(true);
conn.getOutputStream().write(msg.getBytes());
conn.getOutputStream().close();
StringBuilder sb = new StringBuilder();
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()
)
);
String line;
while ((line = in.readLine()) != null)
sb.append(line);
in.close();
return sb.toString();
}
这是 REST API 的 python 代码:
def POST(self,*uri,**params):
if uri[0] == 'userAuth':
tempJson = json.loads(cherrypy.request.body.read())
user_name = tempJson['user_name']
pwd = tempJson['pwd']
if user_name in self.users:
return json.dumps({"user_id":str(self.users.index(user_name)),"result":True})
return json.dumps({"result":"Wrong Credentials","success":False})
在cherrypy服务器上我收到以下错误:
ValueError:无法解码 JSON 对象
问题是我通过 java 流发送数据,但无法在 python 中对其进行解码。
有没有办法直接以字符串形式发送数据或在 python 中对其进行解码?
已解决
修复添加行:
conn.setRequestProperty("Content-Type","application/json");
最佳答案
将您的 POST
方法定义为:
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def POST(self,*uri,**params):
req = cherrypy.request
if uri[0] == 'userAuth':
user_name = req.json['user_name']
pwd = req.json['pwd']
if user_name in self.users:
return {"user_id": str(self.users.index(user_name)), "result": True}
return {"result": "Wrong Credentials","success": False}
有关 json
工具的更多信息 https://docs.cherrypy.org/en/latest/basics.html#dealing-with-json 。同样在android方面...看看https://www.wikihow.com/Execute-HTTP-POST-Requests-in-Android您很可能需要使用 HttpURLConnection
并指定 HTTP 方法 client.setRequestMethod(“POST”);
关于java - Android 和 CherryPy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53417316/