Retrofitの基本的な使い方


Retrofitの基本的な使い方
Retrofitの紹介
RetrofitはSquareが開発したAndroidネットワークリクエストフレームワークであり、OkHttpに基づいて実現されている.他のネットワークフレームワークとは異なり、ランタイム注記を使用して機能します.
Retrofit依存
在 build.gradle構成は次のように依存します.
    implementation 'com.squareup.retrofit2:retrofit:2.6.1'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.1'

最初の行はretrofit依存を構成します.2行目はgson変換依存性を構成した.
Retrofit注記分類
Retrofitには3種類の注釈があります.
  • 要求方法注釈;
  • タグクラス注釈;
  • パラメータクラス注記.

  • Httpリクエストメソッド注記は,GET,POST,PUT,DELETE,HEAD,PATCH,OPTIONS,HTTPの8種類である.
    タグ類注記は、FormUrlEncoded、Multipart、Streamingの3種類.
    パラメータ類注記:Header、Headers、Body、Path、Field、FieldMap、Part、PartMap、Query、QueryMapなど.
    GET要求アクセスネットワーク
    ここでは宝を洗うIPライブラリを例に挙げます.まず、ネットワーク要求インタフェースを定義します.
    public interface IpService {
        @GET("getIpInfo.php?ip=59.108.54.37")
        Call<IpModel> getIpMsg();
    }
    

    コンストラクタモードでRetrofitを構築し、Retrofitダイナミックエージェントを使用して定義されたServiceインタフェースを取得し、インタフェースのgetIpMsgメソッドを呼び出してCallオブジェクトを取得します.
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            IpService ipService = retrofit.create(IpService.class);
            Call<IpModel> call = ipService.getIpMsg();
    

    次にcallを使用します.Enqueueメソッド非同期リクエストネットワーク.
            call.enqueue(new Callback<IpModel>() {
                @Override
                public void onResponse(Call<IpModel> call, Response<IpModel> response) {
                    
                }
    
                @Override
                public void onFailure(Call<IpModel> call, Throwable t) {
    
                }
            });
    

    ここでのCallbackのデフォルトはUIスレッドで実行されます.
    リクエストネットワークを同期したい場合はexecuteメソッドを使用します.
    リクエストをキャンセルするにはcancelメソッドを使用します.
    POST要求アクセスネットワーク
    まず@FormUrlEncoded注記でフォームリクエストであることを示します.次にgetIpMsg法を用いて@Field注記を用いてパラメータStringのキーを示し,キー値ペアのセットを構成して伝達する.
    public interface IpServicePost {
        
        @FormUrlEncoded
        @POST("getIpInfo.php")
        Call<IpModel> getIpMsg(@Field("ip") String first);
    }
    

    Post要求ネットワークのコードは以下の通りである.
        private void doPost() {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(IP_TAOBAO_SERVICE)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            IpServicePost ipServicePost = retrofit.create(IpServicePost.class);
            Call<IpModel> call = ipServicePost.getIpMsg(IP);
            call.enqueue(new Callback<IpModel>() {
                @Override
                public void onResponse(Call<IpModel> call, Response<IpModel> response) {
    
                }
    
                @Override
                public void onFailure(Call<IpModel> call, Throwable t) {
    
                }
            });
        }
    

    メッセージヘッダヘッダ
    HTTPリクエストでは,攻撃や不正なアクセスのフィルタリングを防止したり,特殊暗号化されたアクセスタグを追加したりするために,メッセージヘッダに特殊なメッセージヘッダ処理を携帯する.
    Retrofitは@Header注釈追加メッセージヘッダを提供します.2つの追加方法があります.
  • 静的追加;
  • 動的追加.

  • スタティツクモード
    public interface HeaderStaticService {
    
        @GET("some/endpoint")
        @Headers("Accept-Encoding: application/json")
        Call<ResponseBody> getCarType();
    }
    

    複数のメッセージヘッダを追加する場合は、カッコ{}を使用します.
    public interface HeaderStaticMultiService {
    
        @GET("some/endpoint")
        @Headers({
                "Accept-Encoding: application/json",
                "User-Agent: MoonRetrofit"
        })
        Call<ResponseBody> getCarType();
    }
    

    ダイナミックモード
    public interface HeaderDynamicService {
    
        @GET("some/endpoint")
        Call<ResponseBody> getCarType(@Header("Location") String location);
    }
    

    @Header注記を使用すると、getCarTypeメソッドを呼び出してメッセージヘッダを動的に追加できます.
    まとめ
    Retrofitは、注釈を使用してネットワーク要求機能を提供します.@GET、@POSTメソッドを使用してネットワークにアクセスし、@Headerを使用してメッセージヘッダを追加します.