2017-01-24 4 views
0

私は自分のAPIに簡単なPOSTリクエストを送信したいが、それを行う方法は多々試したが、jsonObjectに書き込む方法はわからない。私は値でのHashMapラップしたい自分のWebServiceへの投稿要求で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 

アンドロイドクラス:

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); 

答えて

0

それはあなたが使用することができます

<String, String> 

だから:

new JSONObject(map); 
+0

を...マップからJSONObjectを取得するために...ではなく、送信とそれが問題だったため。.. 。 – Selvin

関連する問題