使用JSON使用网络GET方法登录应用程序

问题描述 投票:0回答:2

我对Android及其一些核心概念还很陌生。我正在寻找基本的登录屏幕。为了使用户登录http函数(GET),必须使用方法使用JSON对象与服务器一起验证凭据。该用户有2个登录选项。

检查员登录信息:

  • 用户名:admin
  • 密码:管理员

用户登录信息:

  • 用户名:用户
  • 密码:12345

服务器:http://mohameom.dev.fast.sheridanc.on.ca/users/verifyUserData.php?name=user&password=12345

感谢您的提前帮助!

人们将如何去做?

Xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtSignin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="Login"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="@color/colorAccent" />

    <EditText
        android:id="@+id/edtUser"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:layout_marginTop="20dp"
        android:layout_marginHorizontal="30dp"
        android:text=""
        android:hint="Username"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"/>

    <EditText
        android:id="@+id/edtPass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginHorizontal="30dp"
        android:ems="10"
        android:inputType="textPassword"
        android:text=""
        android:hint="Password"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"/>


    <Button
        android:id="@+id/btnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginHorizontal="30dp"
        android:text="Login"
        android:onClick="loginUser"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"/>

</LinearLayout>
android android-networking android-json
2个回答
0
投票
  1. 默认情况下禁止HTTP连接,您应该允许它android:usesCleartextTraffic =“ true”

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
    </activity>
    

  2. 登录活动(Kotlin,从文档复制过来的副本-> https://developer.android.com/training/volley/simple#kotlin]

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        setContentView(R.layout.login)
    
        btnLogin.setOnClickListener {
    
        val queue = Volley.newRequestQueue(this)
        val url =
            "http://mohameom.dev.fast.sheridanc.on.ca/users/verifyUserData.php?name=${edtUser.text}&password=${edtPass.text}"
    
        val stringRequest = StringRequest(
            Request.Method.GET, url,
            Response.Listener<String> { response ->
                txtSignin.text = response.toString() // Process response if needed
            },
            Response.ErrorListener {
                txtSignin.text = "That didn't work!"
            })
        queue.add(stringRequest)
      }
    }
    

0
投票

您可以使用RetrofitVolley进行API调用

注意:在清单的api中为[http中的API添加android:usesCleartextTraffic="true"

  1. 在Gradle中添加翻新依赖项

    dependencies {
      ...
      implementation 'com.squareup.retrofit2:retrofit:2.5.0'
      implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
      ...
    }
    
  2. 创建改造实例类(RetrofitInstance.java)

    public class RetrofitInstance {
    
    private static Retrofit retrofit;
    private static String BASE_URL = "http://mohameom.dev.fast.sheridanc.on.ca/";
    
    /**
     * Create an instance of Retrofit object
     *
     * @param from*/
    public static Retrofit getRetrofitInstance() {
        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    
        return retrofit;
    }
    }
    
  3. 创建接口(GetDataInterface.java)

    public interface GetDataInterface {
    @GET("users/verifyUserData.php")
    Call<ResponseBody> getLogin(@Query("name") String strUserName, @Query("password") String strPassword);
    }
    
  4. 现在登录您的登录名

    • 检查按钮上的验证是否为空,并在需要时进行其他验证
    • 检查互联网连接
    • 如果两个检查都正确,则调用Login API方法(例如callLogin())

        private void callLogin() {
        //open progress
        GetDataInterface service = RetrofitInstance.getRetrofitInstance().create(GetDataInterface.class);
        Call<ResponseBody> call = service.getLogin(strUserName, strPassword);
        call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        try{
           JSONObject resultObj = new JSONObject(response.body().string());
           String strIsValid = resultObj.getString("login");
          //dismiss progress
          //check the condition and direct to next screen(your flow)
          }catch (JSONException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
        }
        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
          //dismiss progress
        }
        } 
      
© www.soinside.com 2019 - 2024. All rights reserved.