如何使用 volley 登录?

How to do login using volley?

我是 Java(android 工作室)的新人。

我尝试使用 Volley 进行 Post http 请求。

我的objective是登录

我做了一些研究,发现发送表单数据的方式是这样的。

但是我迷路了

这是我的完整代码。

build.gradle(模块:应用程序)

    apply plugin: 'com.android.application'

    android {
        compileSdkVersion 30
        buildToolsVersion "30.0.1"
    defaultConfig {
        applicationId "com.example.homesweethome"
        minSdkVersion 19
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation "com.android.volley:volley:1.1.1"

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.homesweethome">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

MainActivity.java

  package com.example.homesweethome;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {


    /* Define the UI elements */
    private EditText eName;
    private EditText ePassword;
    private TextView eAttemptsInfo;
    private Button eLogin;

    private RequestQueue mRequestQueue;
    private String url = "https://apisguatukang.spatialworks.com.my/login";
    private static final String TAG = MainActivity.class.getName();

    String userName = "";
    String userPassword = "";



    boolean isValid = false;

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

        /* Bind the XML views to Java Code Elements */
        eName = findViewById(R.id.idUsername);
        ePassword = findViewById(R.id.idPassword);
        eLogin = findViewById(R.id.buttonLogin);

        /* Describe the logic when the login button is clicked */
        eLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                /* Obtain user inputs */
                userName = eName.getText().toString();
                userPassword = ePassword.getText().toString();


                /* Check if the user inputs are empty */
                if(userName.isEmpty() || userPassword.isEmpty())
                {
                    /* Display a message toast to user to enter the details */
                    Toast.makeText(MainActivity.this, "Please enter name and password!", Toast.LENGTH_LONG).show();

                }else {

                    validate(userName, userPassword);
                    
                   

                }
            }
        });
    }

    /* Validate the credentials */
    private void validate(final String userName, final String userPassword)
    {
          mRequestQueue = Volley.newRequestQueue(MainActivity.this);

        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response != null) {
                    Log.i(TAG, "onResponse: " + response);
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "onErrorResponse: " + error);
                    }
                }){

            @Override
            protected Map<String,String> getParams() throws AuthFailureError {
                HashMap<String,String> params = new HashMap<>();
                params.put("username",userName.trim());
                params.put("password",userPassword.trim());
                Log.i(TAG, "getParams: "+ params);
                return params;
            }

        };

        mRequestQueue.add(request);
    }
}

Post 请求使用 Postman

您需要使用此字符串请求方法 post 您的登录请求,您需要将参数与请求映射。 下面显示了示例代码,其中包含您需要更改的某些注释。希望对你有帮助。

StringRequest request = new StringRequest(Request.Method.POST, //your url here// , response -> {
    
                        if(response != null){

                             /////do something here/////
    
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
    
                    }, error -> {
                        error.printStackTrace();
                        
                    }) {
                        //// pass parameters id and password here////
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            HashMap<String, String> map = new HashMap<>();
                            map.put("email", id.getText().toString().trim());
                            map.put("password", pass.getText().toString().trim());
                            return map;
                        }
                    };
    
                    RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
                    queue.add(request);

看我下面的源码

//Creating a string request
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.LOGIN_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.d("Response",""+response);
                        //If we are getting success from server
                        if (response.equals("success")) {
                            //Creating a shared preference

                            SharedPreferences sp = LoginActivity.this.getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);

                            //Creating editor to store values to shared preferences
                            SharedPreferences.Editor editor = sp.edit();
                            //Adding values to editor
                            editor.putString(Constant.ROLL_SHARED_PREF, roll);

                            //Saving values to editor
                            editor.apply();

                            //Starting Home activity
                            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                            startActivity(intent);
                            Toast.makeText(LoginActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();

                        }




                        else if(response.equals("failure")) {
                            //If the server response is not success
                            //Displaying an error message on toast
                            Toast.makeText(LoginActivity.this, "Roll or Password is not valid", Toast.LENGTH_LONG).show();
                        }

                        else {
                            //If the server response is not success
                            //Displaying an error message on toast
                            Toast.makeText(LoginActivity.this, "Invalid user cell or password", Toast.LENGTH_LONG).show();
                        }
                    }
                },

                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //You can handle error here if you want

                        Toast.makeText(LoginActivity.this, "There is an error !!!", Toast.LENGTH_LONG).show();
                        loading.dismiss();
                    }
                }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                //Adding parameters to request
                params.put(Constant.KEY_ROLL, roll);
                params.put(Constant.KEY_PASSWORD, password);

                //returning parameter
                return params;
            }
        };

        //Adding the string request to the queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

我从 git repository 中获取了这个源代码 也许如果你访问以下link,你会更正确地理解它。

Volley login activity