2016-06-13 28 views
1

我正在開發一個android應用程序,並試圖將「用戶名」和「密碼」參數發佈到要處理的服務器上。如何在PHP中通過Volley發送PHP中的HashMap?

我已經在Java中使用volley將哈希映射發送到服務器,因爲我發現如何通過外部研究來做到這一點。

final HashMap<String, String> dataToSend = new HashMap<>(); //Contains key/value pairs of data we will send to the server 
            //Add the data to the data package 
            dataToSend.put("username", username); //Add username to the package 
            dataToSend.put("password", password); //Add password to the package 
            final String url = "url here"; //The url we will make the delivery to. 

            //Making the object request, parsing the data to send to the server 
            JsonObjectRequest loginRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(dataToSend), new Response.Listener<JSONObject>() { 
             @Override 
             public void onResponse(JSONObject response) { 
              login_progress_dialog.dismiss(); 
              try { 
               Toast.makeText(getContext(), "You said: " + response.getString("username"), Toast.LENGTH_SHORT).show(); 
              } 
              catch (Exception e){ 
               Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show(); 
              } 
             } 
            }, new Response.ErrorListener() { 
             @Override 
             public void onErrorResponse(VolleyError error) { 
              //An error occurred during transmission, log to console and notify user. 
              login_progress_dialog.dismiss(); 
              Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show(); 
             } 
            }); 

            RequestQueue loginRequestQueue = Volley.newRequestQueue(getContext()); 
            loginRequestQueue.add(loginRequest); //Add the above request to the queue for execution. 

然後我的服務器上有我的PHP腳本,通過url中的volley通過https調用。 目前我所需要做的就是從hashMap中取出用戶名和密碼,但出於安全原因,不使用GET

我不知道該怎麼做,也無法在網上找到任何幫助。 這裏是PHP,因爲它代表的時刻:

<?php 
    $username = $_POST["username"]; 
    $response = json_encode(array('username' => $username)); 
    echo $response; 
?> 

上面總是返回null?我如何將數據從HashMap中獲取到PHP腳本中?我認爲問題出在我的PHP上,但我不確定。

回答

0

我想你應該在此改變以下方法要求如下面

@Override 
     protected Map<String,String> getParams(){ 
      Map<String,String> params = new HashMap<String, String>(); 
      params.put(KEY_USERNAME,username); 
      params.put(KEY_PASSWORD,password); 
      params.put(KEY_EMAIL, email); 
      return params; 
     } 
+0

謝謝,我只是回答我的問題。已標記爲正確,因爲它是相同的解決方案。 –