我正在开发一个 Android 应用程序,并尝试将“用户名”和“密码”参数发布到服务器进行处理。
我在 Java 中使用 volley 向服务器发送 hashMap 来完成此操作,因为我通过外部研究发现了如何做到这一点。
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 中的 https 从 volley 调用。 目前,出于安全原因,我需要做的就是从 hashMap 中获取用户名和密码,而不使用 GET。
我不知道该怎么做,也无法在网上找到任何帮助。 这是目前的 PHP 情况:
<?php
$username = $_POST["username"];
$response = json_encode(array('username' => $username));
echo $response;
?>
上面总是返回null?如何将数据从 HashMap 获取到 PHP 脚本中?我认为问题出在我的 PHP 上,但我不确定。
最佳答案
我认为您应该在请求中覆盖以下方法,如下所示
@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;
}
关于java - 如何在 PHP 中获取通过 Volley 发送的 PHP 中的 HashMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37784343/