java Android和CherryPy
我正在开发一个Android应用程序,其中我必须在用cherrypy构建的RESTAPI上发出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: No JSON object could be decoded
问题是,我通过java流发送数据,但无法用python对其进行解码。
有没有一种方法可以将数据直接作为字符串发送,或者用python对其进行解码
已解决
修正了添加行的问题:
conn.setRequestProperty("Content-Type","application/json");
# 1 楼答案
将
POST
方法定义为:有关
json
工具https://docs.cherrypy.org/en/latest/basics.html#dealing-with-json的更多信息。同样在安卓方面。。。查看一下https://www.wikihow.com/Execute-HTTP-POST-Requests-in-Android最有可能需要使用HttpURLConnection
并指定HTTP方法client.setRequestMethod(“POST”);