0
1

More than 3 years have passed since last update.

Retrofit2とOkhttp3とGsonを使用してAPIを作成(Java)

Posted at

API作成時の備忘録。
細かい説明は抜きにして、とりあえずこれで通信できた。

手順

  • manifestfileに通信を許可するように設定
  • リクエスト、レスポンスを受け取る用のクラスを定義
  • エンドポイントの作成
  • HTTPクライアントの作成
  • 実行

manifestFileに通信を許可するように設定

AndroidManifest.xml に以下を記述する

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

リクエスト、レスポンスを受け取る用のクラスを定義

ログイン用のリクエストクラス、 requestのbodyがこの形式で送られる

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がこの形で受け取られる

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;
    }
}

エンドポイントを作成する

interfaceを作成

RequestApiService

public interface RequestApiService {
    @POST("/login") // API エンドポイント
    Call<LoginResponse> logIn(@Body LoginRequest requestBody); 
    // logInメソッドが呼ばれると,body形式は上記で作った、LoginRequestクラスの形になる
}

HTTPクライアントの作成

HttpClient.java
public class HttpClient {
    public static RequestApiService apiService;

    private static final String URL = "http://baseurl"; // 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();

    // RetrofitにGSONとOkhttpを組み合わせてHttpクライアントの作成
    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;
    }

実行

SignInFragment.java

private boolean starLogin(String emailStr, String passwordStr) {
        // bodyの作成
        LoginRequest requestBody = new LoginRequest(emailStr, passwordStr);
        // HTTPクライアントの呼び出し
        RequestApiService apiService = HttpClient.getRequestApiService();

        // 通信開始 interfaceで定義した処理が呼ばれる
        apiService.logIn(requestBody).enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if (response.isSuccessful()) {
                   // 通信処理成功時の処理を記載
                } else {
                    Log.e("SignInFragment", "Something wrong On Response: " + response.toString());   
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                // 通信処理失敗時の処理を記載
            }
        });
        return true;
    }

所感

tokenの保持とか、成功失敗時の処理とかまだあるが、とりあえずこれで通信はできた。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1