Create API using Retrofit2, Okhttp3 and Gson (Java)

A memorandum when creating the API. I was able to communicate with this for the time being, without detailed explanation.

procedure

--Set manifestfile to allow communication --Define a class for receiving requests and responses --Create endpoint --Create HTTP client --Execute

Set manifestFile to allow communication

AndroidManifest.Write the following in xml




#### **`AndroidManifest.xml`**
```java

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

Define a class for receiving requests and responses

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 an 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 the form 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 an Http client by combining Retrofit with 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;
    }

Run

SignInFragment.java



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

        //Communication start: 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()) {
                   //Describes 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) {
                //Describes the processing when communication processing fails
            }
        });
        return true;
    }

Impressions

There are still things like holding tokens and processing when success or failure occurs, but for the time being, communication was possible.

Recommended Posts

Create API using Retrofit2, Okhttp3 and Gson (Java)
Notes on implementing google books api in java okhttp and gson versions and okhttp and jackson versions
Create a portfolio app using Java and Spring Boot
Tips for using Salesforce SOAP and Bulk API in Java
Let's create a file upload system using Azure Computer Vision API and Azure Storage Java SDK
Export issues using JIRA's Java API
Create a Java project using Eclipse
I tried using Java8 Stream API
[Android] Convert Map to JSON using GSON in Kotlin and Java
[Java] Create and apply a slide master
Data processing using stream API from Java 8
Try using the Stream API in Java
Nowadays Java lambda expressions and Stream API
Java implementation to create and solve mazes
Try using JSON format API in Java
Create a RESTful API service using Grape
Java and Derby integration using JDBC (using NetBeans)
Install Docker and create Java runtime environment
[Java] Get and display the date 10 days later using the Time API added from Java 8.
Interact with LINE Message API using Lambda (Java)
Create barcodes and QR codes in Java PDF
Install java and android-sdk on Mac using homebrew
Let's create a REST API using WildFly Swarm.
ChatWork4j for using the ChatWork API in Java
[Java] API creation using Jerjey (Jax-rs) in eclipse
[Java] Create something like a product search API
Try using GCP's Cloud Vision API in Java
Date and time acquisition method using DateAndTime API
Try using the COTOHA API parsing in Java
[Java] How to operate List using Stream API
Java Stream API
Java and JavaScript
XXE and Java
Place "Create a to-do list using Rails API mode and React Hooks" on docker
Create a Java development environment using jenv on Mac
Convert JSON and YAML in Java (using Jackson and SnakeYAML)
I tried Mastodon's Toot and Streaming API in Java
[Java] Sort the list using streams and lambda expressions
[In-house study session] Java basics-Lambda expression and Stream API- (2017/07/13)
I tried using Google Cloud Vision API in Java
Install java and maven using brew on new mac
Create two or more line graphs using MPAndroidChart [Java]
Create environment-independent war file using Maven profiles and maven-war-plugin
Examine HTML elements and create Page class (using Selenide)
How to convert A to a and a to A using AND and OR in Java
[Rails] Create sitemap using sitemap_generator and deploy to GAE
[Java] Convert JSON to Java and Java to JSON-How to use GSON and Jackson-
Create a JAVA WEB application and try OMC APM
Mutual conversion between Java objects and JSON using Moshi
[Java10] Be careful of using var and generics together
[Java] Development with multiple files using package and import