Вход в приложение с помощью метода Networking GET с использованием JSON - PullRequest
0 голосов
/ 02 декабря 2019

Я довольно плохо знаком с Android и некоторыми из его основных концепций. Я ищу простой экран входа в систему. Чтобы пользователь мог войти в http функции (GET), необходимо использовать методы для проверки учетных данных на сервере с использованием объекта JSON. У пользователя есть 2 варианта входа в систему.

Информация для входа в Examiner:

  • Имя пользователя: admin
  • Пароль: 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>

Ответы [ 2 ]

1 голос
/ 02 декабря 2019
  1. HTTP-соединение запрещено по умолчанию, вы должны разрешить его android: использованииCleartextTraffic = "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 голосов
/ 02 декабря 2019

Вы можете использовать Retrofit или Volley для вызова API

Примечание: Добавить android:usesCleartextTraffic="true" в манифест для API в http

  1. Добавить зависимость Retrofit в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. Теперь на вашем Классе входа

    • Проверьте проверку нажатия кнопки для Очистить и любую другую проверку, если необходимо
    • Проверьте подключение к Интернету
    • если обе проверки верны, то вызвать метод 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
        }
        } 
      
...