gpt4 book ai didi

java - 如何在发布请求中将 hashmap 作为 jsonObject 发送到自己的 WebService

转载 作者:太空宇宙 更新时间:2023-11-04 11:51:01 25 4
gpt4 key购买 nike

我想向我自己的 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);

关于java - 如何在发布请求中将 hashmap 作为 jsonObject 发送到自己的 WebService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41836620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com