如何在post请求中将hashmap作为jsonObject发送给自己的WebService

时间:2017-01-24 18:44:39

标签: java android

我想将简单的POST请求发送到我自己的API,我尝试了很多方法,但我不知道如何将它包装到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);

1 个答案:

答案 0 :(得分:0)

好吧,因为它是

<String, String> 

你可以使用:

new JSONObject(map);