如何使用 volley 登录?

如何解决如何使用 volley 登录?

我是 Java 新手(android studio)。

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

我的目标是登录

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

但我迷路了。

这是我的完整代码

build.gradle(Module:app)

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

使用 Postman 的 Post 请求

enter image description here

解决方法

看我下面的源码

//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 也许如果您访问以下链接,您会更正确地理解它。

Volley login activity

,

您需要使用这个字符串请求方法来发布您的登录请求,您需要将参数与请求映射起来。 示例代码如下所示,其中包含您需要更改的某些注释。希望它会有所帮助。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?