【问题标题】:send params from volley android to php with post method使用 post 方法将参数从 volley android 发送到 php
【发布时间】:2017-01-29 20:09:00
【问题描述】:

我想通过 volley 将参数发送到主机中的 php 页面。但我收到以下错误。

BasicNetwork.performRequest: Unexpected response code 400

这是我的 php 代码

<?php

if ($_SERVER['REQUEST_METHOD']=='POST'){
    $user = $_POST['email'];
    $pass = $_POST['password'];

    $sql = "select * from users where email = '$user' AND password = '$pass'";

    require_once('config.php');
    $result = mysqli_query($con , $sql);
    $check = mysqli_fetch_array($result);

    if(isset($check)){
        echo "success";
    }else{
        echo "failure";
    }
    mysqli_close($con);
}
?>

这是文件 config.php

<?php
$serverName = "localhost";
$userName = "root";
$password = "";
$dbName = "testDb"

$con = mysqli_connect($serverName , $userName , $password , $dbName) or die("connect failed");
?>

这是我的安卓代码

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);
        buttonLogin = (Button) findViewById(R.id.buttonLogin);
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();

        SharedPreferences sharedPreferences = getSharedPreferences(config.SHARED_PREF_NAME , Context.MODE_PRIVATE);
        loggedIn = sharedPreferences.getBoolean(config.LOGGEDIN_SHARED_PREF , false);
        Log.e("txt" , "text is : " + loggedIn);
        if (loggedIn){
            Intent intent = new Intent(loginActivity.this , profileActivity.class);
            startActivity(intent);
        }
    }

    private void login(){

        final String email = editTextEmail.getText().toString().trim();
        final String password = editTextPassword.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, config.LOGIN_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("StartActivity", response.toString());
                if(response.equalsIgnoreCase(config.LOGIN_SUCCESS)){
                    //Creating a shared preference
                    SharedPreferences sharedPreferences = loginActivity.this.getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

                    //Creating editor to store values to shared preferences
                    SharedPreferences.Editor editor = sharedPreferences.edit();

                    //Adding values to editor
                    editor.putBoolean(config.LOGGEDIN_SHARED_PREF, true);
                    editor.putString(config.EMAIL_SHARED_PREF, email);
                    //Saving values to editor
                    editor.commit();

                    //Starting profile activity
                    Intent intent = new Intent(loginActivity.this, profileActivity.class);
                    startActivity(intent);
                }else{
                    //If the server response is not success
                    //Displaying an error message on toast
                    Toast.makeText(loginActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
                    Log.e("s" , "invalid sssssssssssssssssssssss");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            public Map<String, String> getParams() {
                Map<String,String> params = new HashMap<>();
                params.put(config.KEY_EMAIL, email);
                params.put(config.KEY_PASSWORD, password);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

当它运行时 onResponse else 命令被执行。 带有post方法值的传输参数是错误的

谢谢

【问题讨论】:

    标签: php android android-volley


    【解决方案1】:

    BasicNetwork.performRequest:意外响应代码 400

    400 表示请求格式不正确。也就是说,客户端发给服务端的数据流不符合规则。

    错误原因:

    您忘记在$dbName 后面加上分号,这会导致数据库一次又一次地死掉,而不会通过登录链接显示任何Exception,正确:

    $dbName = "testDb"; //<--here forgot to add semicolon
    

    更正 - 尝试代码:

    @Override
     public Map<String, String> getParams() {
      Map<String,String> params = new HashMap<>();
      params.put("user", email);     //here
      params.put("pass", password);  //here
      return params;
     }
    };
    

    更正 - 在与表格交互之前需要一次:

    <?php
    $user = $_POST['email'];
    $pass = $_POST['password'];
    
    require_once('config.php'); //here
    
    $sql = "select * from users where email = '$user' AND password = '$pass'";
    

    【讨论】:

    • 好的,现在我正在测试
    • BasicNetwork.performRequest:librarylib.gigfa.com/login.php 的意外响应代码 400
    • 必须使用post参数的方式提交才能打印成功信息
    • 我想我找到了答案,您的数据库上还有其他操作吗?
    【解决方案2】:

    不要覆盖getParams(),而是尝试覆盖getBodyContentType()getBody()

    类似这样的:

    StringRequest stringRequest = new StringRequest(Request.Method.POST, config.LOGIN_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("StartActivity", response.toString());
            if(response.equalsIgnoreCase(config.LOGIN_SUCCESS)){
                //Creating a shared preference
                SharedPreferences sharedPreferences = loginActivity.this.getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
    
                //Creating editor to store values to shared preferences
                SharedPreferences.Editor editor = sharedPreferences.edit();
    
                //Adding values to editor
                editor.putBoolean(config.LOGGEDIN_SHARED_PREF, true);
                editor.putString(config.EMAIL_SHARED_PREF, email);
                //Saving values to editor
                editor.commit();
    
                //Starting profile activity
                Intent intent = new Intent(loginActivity.this, profileActivity.class);
                startActivity(intent);
            }else{
                //If the server response is not success
                //Displaying an error message on toast
                Toast.makeText(loginActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
                Log.e("s" , "invalid sssssssssssssssssssssss");
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
    
        }
    }){
        @Override
        public byte[] getBody() throws AuthFailureError {
            final JSONObject body = new JSONObject();
            try {
                body.put(config.KEY_EMAIL, email);
                body.put(config.KEY_PASSWORD, password);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return body.toString().getBytes();
        }
    
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type","application/json");
            return headers;
        }
    };
    

    检查这个问题:StringRequest with JSON body

    【讨论】:

    • 传输的数据不是json的类型
    • @Ali 那么是什么类型的?
    • 传输的数据是字符串类型
    • @Ali 您是否尝试过使用上述代码?查看您的参数表明您不应该对内容类型为 application/json 有任何问题
    • 我已经更新了 getBody 方法来发送你的参数。
    猜你喜欢
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2015-07-21
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多