[Java] Create API using Retrofit2, Okhttp3 and Gson (Java)

1 minute read

A memorandum when creating an API. I could communicate with this for the time being, without detailed explanation.

procedure

  • Set the manifest file to allow communication
  • Define a class for receiving requests and responses
  • Create endpoint
  • Create HTTP client
  • Run

Set manifestFile to allow communication

Describe the following in AndroidManifest.xml

AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET" />

Define class for receiving request and response

Request class for login, body of request is sent in this format

LoginRequest.java


package com.example.bookmanager_android.models.requests;

public class LoginRequest {
    private String email;
    private String password;

    public LoginRequest(String email, String passWord){
        this.email = email;
        this.password = passWord;
    }
}
  • Response class

Response class for login, response is received in this form

LoginResponse.java


package com.example.bookmanager_android.models.requests.response;

public class LoginResponse {
    public int status;
    public Result result;

    public static class Result {
        public int id;
        public String email;
        public String token;
    }
}

Create endpoint

create interface

RequestApiService



public interface RequestApiService {
    @POST("/login") // API endpoint
    Call<LoginResponse> logIn(@Body LoginRequest requestBody);
    // When the logIn method is called, the body format will be that of the LoginRequest class created above
}

Creating an HTTP client

HttpClient.java


public class HttpClient {
    public static RequestApiService apiService;

    private static final String URL = "http://baseurl"; // specify BaseUrl

    // Okhttp
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();
    // GSON
    private static final Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();

    // Create Retrofit Http client by combining GSON and Okhttp
    public static RequestApiService getRequestApiService() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build();
        apiService = retrofit.create(RequestApiService.class);
        return apiService;
    }

execute

SignInFragment.java



private boolean starLogin(String emailStr, String passwordStr) {
        // create body
        LoginRequest requestBody = new LoginRequest(emailStr, passwordStr);
        // HTTP client call
        RequestApiService apiService = HttpClient.getRequestApiService();

        // Start communication: The process defined in interface is called
        apiService.logIn(requestBody).enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if (response.isSuccessful()) {
                   // Describe the processing when communication processing is successful
                } else {
                    Log.e("SignInFragment", "Something wrong On Response: "+ response.toString());
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                // Describe the processing when communication processing fails
            }
        });
        return true;
    }

Remarks

I still have token holding and success/failure processing, but for the time being I was able to communicate.