Retrofitに対する学習のまとめ


友人の余震涛のブログによると
Android学習のネットワークリクエストライブラリのRetrofit 2
学習と学習の心得をまとめた.
実装プロセス:
1.gradleインポートに必要なライブラリ.
compile 'com.squareup.okhttp3:okhttp:3.2.0' compile 'com.squareup.retrofit2:retrofit:2.0.0' compile 'com.squareup.retrofit2:converter-gson:2.0.0' compile 'com.google.code.gson:gson:2.6.2'

2.サーバの相対的なBeanオブジェクトを作成します.
3.Beanの相対的なRetrofitインタフェースを作成し、入力するパラメータを予約します.
public interface PhoneService {

    @GET("/apistore/mobilenumber/mobilenumber")
    Call<PhoneResult> getResult(@Header("apikey") String apikey, @Query("phone") String phone);  }

4.サーバデータの取得
4.1 Retrofitオブジェクトを作成し、サーバアドレスを入力します.4.2 Callを取得するインタフェースオブジェクトを作成し、対応するclassを入力します.4.3 Callオブジェクトをインタフェースで取得し、様々なgetフィールド(ブロガーが言うAPIアドレスもgetの要求keyである)を入力する.4.4 callによるenqueueサーバの結果.4.5取得に成功し、取得したresponseを操作します.
private void query1() {
    //  Retrofit  ,         Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(BASE_URL).build();  //    Call     ,      class  PhoneService phoneService = retrofit.create(PhoneService.class);  //      Call  ,  api   get   ,      api      。  Call<PhoneResult> phoneResultCall = phoneService.getResult(API_KEY, et1.getText().toString());  //  call enqueue       phoneResultCall.enqueue(new Callback<PhoneResult>() {
        @Override  public void onResponse(Call<PhoneResult> call, Response<PhoneResult> response) {
            if (response.isSuccessful()) {
                //       body   。  PhoneResult phoneResult = response.body();  if (phoneResult != null) {
                    PhoneResult.RetDataEntity retDataEntity = phoneResult.getRetData();  Toast.makeText(context, retDataEntity.getCity(), Toast.LENGTH_SHORT).show();  }
            }
        }

        @Override  public void onFailure(Call<PhoneResult> call, Throwable t) {
        }
    }); }

また,ソースコードを調べると,Retrofitではbody()メソッドのほかに,返されるmsg,code,headerなどの要素を取得できることが分かった.使い勝手がよい.
その後,Retrofitを用いてput,postなどのネットワークリクエストを実現する方法も検討する必要がある.