Как войти в систему с помощью retrofit2, используя метод GET

Я использую API для входа

http://abc.demoserver.com/API/login.php?username=johndoe&password=123456

этот API в методе GET

а также с помощью retrofit2, так что мой фрагмент кода здесь.

APIUtils.java

public static final String BASE_URL = "http://abc.demoserver.com/API/";

public static APIService getAPIService() {
    return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}

APIServiceInterface.java

@GET("login.php")
Call<JsonObject> studentLogin(@Query("username") String username,
                              @Query("password") String password);

и мой RetrofitClient.java

public class RetrofitClient {

private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl) {
    if (retrofit == null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
  }
}

Это дает мне нулевой ответ, но когда я нажимаю на этот URL в браузере, он дает response в нижнем формате

{
  "details": [
    {
      "ID": "56895",
      "user_login": "johndoe",
      "user_pass": "$P$BPjOjHab\iHVP0/YPOIly.b1",
      "user_email": "abc@xyz.com",
      "user_registered": "2017-02-10 07:28:39",
      "user_status": "0",
      "display_name": "John Doe",
      "instructor": "23",
      "token": "212cde4b85163cbd05962ef",
      "profile_img": "http://abc.demoserver.com/wp-content\/uploads\/avatars\/16895\/165113b6b900b4cf145b84c31.jpg"
    }
  ],
  "status_code": 1,
  "status_description": "Login successful."
}

ОБНОВЛЕНО

Перезвоните

public void loginData(String username, String password) {
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setMessage("Please wait...");
    dialog.setCancelable(false);
    dialog.show();

    apiService.studentLogin(username, password).enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {

            dialog.dismiss();

            try {
                if (response != null) {
                    JSONObject josn = new JSONObject(response.body().toString());

                    JSONArray jarray = josn.getJSONArray("details");
                    for (int i = 0; i < jarray.length(); i++) {

                        JSONObject jsonObject = jarray.getJSONObject(0);

                        user_id = jsonObject.getString("ID");
                        user_name = jsonObject.getString("user_login");
                        user_mail = jsonObject.getString("user_email");
                        user_display_name = jsonObject.getString("display_name");
                        user_registered = jsonObject.getString("user_registered");
                        user_status = jsonObject.getString("user_status");
                        token = jsonObject.getString("token");
                        instructor = jsonObject.getString("instructor");
                        user_pass = jsonObject.getString("user_pass");
                        profile_img = jsonObject.getString("profile_img");
                    }

                }

            } catch (Exception e) {
                e.printStackTrace();
                Log.e("Exception", e.getMessage());
            }

        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.e("onFailure", "Unable to get API." + t.getMessage());
            dialog.dismiss();
        }
    });
}

как вызвать метод GET API в retrofit2

2 ответа

В первую очередь скопируйте ответ вашего API и создайте классы бина через

этот сайт * Нажав тип источника в JSON * Стиль аннотации в GSON * Снятие пометки useDoubleNumbers * Снятие пометки свойства AllowAdition

затем скопируйте эти файлы в свой проект

тогда в вашей деятельности

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
APIServiceInterface apiController = retrofit.create(APIServiceInterface.class);
Call<Bean> result = apiController.studentLogin(username,password);

result.enqueue(new Callback<Bean>() {
    @Override
    public void onResponse(Call<Bean> call, Response<Bean> response) {
         // you  will get the reponse in the response parameter

    }

    @Override
    public void onFailure(Call<Bean> call, Throwable t) {

    }
});

Создайте класс PoJo из полученного вами ответа и установите для этого класса тип ответа в методе studentLogin, например так

    @GET("login.php")
Call<Result> studentLogin(@Query("username") String username,
                              @Query("password") String password);

где result - ваш класс Pojo, который вы создадите из своего ответа json, используя Json для генератора pojo

Другие вопросы по тегам