我想向我自己的 API 发送简单的 POST 请求,我已经尝试了很多方法来做到这一点,但我不知道如何将其包装到 jsonObject 中。
我想用值包装 HashMap:{“登录”:“登录”,“密码”:“密码”}但它不起作用
API方法:
@app.route('/login', methods=['POST'])
def login():
requestData = None
responseData = None
status = 400
requestDataRead = False
try:
requestData = json.loads(request.data)
requestDataRead = True
except:
responseData = {'error': 'could not read request from client'}
if requestDataRead:
if 'login' in requestData and 'password' in requestData:
if requestData['login'] in usersDict:
if usersDict[requestData['login']]['password'] == requestData['password']:
responseData = {
'info': "OK",
'token': usersDict[requestData['login']]['token'],
'userID': usersDict[requestData['login']]['userID']
}
status = 200
else:
responseData = {'error': 'invalid login or password'}
else:
responseData = {'error': 'there isnt that user in database'}
else:
responseData = {'error': 'empty login or password'}
responseJsonData = json.dumps(responseData)
responseHeaders = {'Content-Type': 'application/json'}
response = Response(responseJsonData,
status=status,
mimetype="application/json",
headers=responseHeaders)
return response
Android 类:
String urlString = "http://10.0.2.2:5000/login";
AsyncHttpClient client = new AsyncHttpClient();
Map<String, String> map = new HashMap<String, String>();
map.put("login", login);
map.put("password", password);
RequestParams params = new RequestParams(map);
client.post(urlString, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(new String(responseBody));
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(jsonObject.toString());
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(new String(responseBody));
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(jsonObject.toString());
}
});
我也尝试过以这种方式传递数据:
RequestParams params = new RequestParams(map);
params.put("login", login);
params.put("password", password);
既然是
<String, String>
您可以使用:
new JSONObject(map);
我是一名优秀的程序员,十分优秀!