Retrofit2 of Network Framework

Keywords: Retrofit network ButterKnife Android

Retrofit2 of Network Framework

Summary

  • Restrofit framework is a network framework produced by Square Company. With annotations and dynamic proxy, it greatly simplifies the tedious steps of network requests and is very suitable for handling Restful network requests.
  • Main features:
    1. Good performance, fast processing, simple use. One of the most popular Http libraries in android today (faster than Volley)
    2. Easy to use Rest api
    3. NIO support (the new IO API can replace the standard Java IO API)
    4. Retrofit handles network requests by default using OKHttp and Gson parsing by default

How to quote

  • Add a reference to build.gradle
  • compile 'com.squareup.retrofit2:converter-gson:2.1.0'
  • After synchronization, add:

Common Annotation Interfaces in Retrofit2

  1. @ GET GET Network Request Mode
  2. @ Headers header information parameters
  3. @ Path path parameters. Replace the parts enclosed by "{" and "}" in url
  4. @ Query query parameters. A string similar to "name=user" will be appended to the url address to form the request parameters submitted to the server side.
  5. @ QueryMap query parameter set. Add a string like "page = 1 & size = 20" to the url address
  6. @ Url URL parameter, no content after @Get at this time

  7. @ POST POST Network Request Mode

Usage of Http

The specific steps are as follows
  1. Define an interface (encapsulating url addresses and data requests)
  2. Instance Retrofit
  3. Creating Interface Service Objects through Retrofit
  4. The interface service object calls the method in the interface to get the Call object
  5. Call objects execute requests (asynchronous, synchronous requests)
Definition in Url in Retrofit 2
  1. To sum up:
    1. The basic url should end with/
    2. path splicing should not start with/
Writing Interface in Get Network Request
  1. Get request, method without parameters

    @GET("article/list/latest?page=1")
    Call<ResponseBody> getData();
    
  2. Get request, in which the @Path parameter and @Query parameter are specified. @ The path parameter is used to replace the {} part of the url, and @Query appends a string similar to "page=1" to the URL address.

    @GET("article/list/{type}?")
    Call<QSBean> getInfoData(@Path("type") String type, @Query("page") int page);
    
  3. Get request, submit form data. Method defines the @QueryMap parameter. @ QueryMap adds a string like "type = text & count = 30 & page = 1" to the url address.

    @GET("lll/register")
    Call<ResponseBody> getRegInfo(@QueryMap Map<String, String> map);
    
  4. Get request, no parameters in the method. However, the complete path is defined in @Get, in which case baseurl is ignored

    @GET("http://img4q.duitang.com/uploads/people/201604/15/20160415120706_BT8UE.jpeg")
    Call<ResponseBody> getImg();
    
  5. Get request, @Url usage

    @GET
    Call<ResponseBody> getImg(@Url String url);
    
  6. Retrofit downloads files and reads them directly into memory, so if the downloaded files are large, OOM exceptions will be reported. In order to avoid the occurrence of OOM, large files need to be downloaded to memory and saved to sd card.

    @Streaming
    @GET
    Call<ResponseBody> getBigData(@Url String url);
    
Writing in Post Access Interface
  1. @ Field parameter; specify the name of the form control, respectively.

    @FormUrlEncoded
    @POST("app/gift/gift_list/")
    Call<ResponseBody> postGiftList(@Field("platform") String platform,
                                @Field("gifttype") String gifttype,
                                @Field("compare") String compare);
    
  2. @ FieldMap parameter: Specify all form control names through the map collection

    @FormUrlEncoded
    @POST("app/gift/gift_list/")
    Call<ResponseBody> postGiftListMap(@FieldMap Map<String, String> map);
    
  3. @ Part parameter: specify the name of the file control and the name of the uploaded file

  4. @ Body parameter: Upload multiple files and other form domain data to the server

The code is as follows:

IService

public interface IService {

    //=======================================================================
    // GET request mode
    //=======================================================================
    @GET("v2/channels/100/items?limit=20&ad=2&gender=1&offset=0&generation=1")
    Call<ResponseBody> getData();

    @GET("article/list/{type}?")
    Call<ResponseBody> getInfoData(@Path("type") String type, @Query("page") int page);

    @GET("article/list/{type}?")
    Call<QSBean> getBeanData(@Path("type") String type, @Query("page") int page);

    @GET("v2/channels/100/items?")
    Call<ResponseBody> getQueryData(@QueryMap Map<String, String> map);

    @GET
    Call<ResponseBody> getImg(@Url String url);


    //=======================================================================
    // Post mode
    //=======================================================================
    //`platform=2&gifttype=1&compare=60841c5b7c69a1bbb3f06536ed685a48
    @FormUrlEncoded
    @POST("app/gift/gift_list/")
    Call<ResponseBody> postField(@Field("platform") int platform,
                                 @Field("gifttype") int type,
                                 @Field("compare") String compare);

    @FormUrlEncoded
    @POST("app/gift/gift_list/")
    Call<ResponseBody> postFieldMap(@FieldMap Map<String, String> params);

}

Constant

public interface Constant {

    //
    String BASE_URL = "http://api.liwushuo.com/";

    String BASE_URL_QB = "http://m2.qiushibaike.com/";

    String BASE_URL_PIC = "http://img4q.duitang.com/";

    String BASE_URL_GIFT="http://zhushou.72g.com/";
}

GetActivity

public class GetActivity extends AppCompatActivity {

    @BindView(R.id.tv_result)
    TextView mTvResult;
    @BindView(R.id.btn_get_url)
    Button mBtnGetUrl;
    @BindView(R.id.btn_query)
    Button mBtnQuery;
    @BindView(R.id.btn_querymap)
    Button mBtnQuerymap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get);
        ButterKnife.bind(this);

    }


    @OnClick({R.id.btn_get_url, R.id.btn_query, R.id.btn_querymap})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_get_url:
                loadGetData();
                break;
            case R.id.btn_query:
//                queryInfo();
                queryData();
                break;
            case R.id.btn_querymap:
                queryMapData();
                break;
        }
    }


    private void loadGetData() {
        //2. Create Retrofit instance objects
        //A basic url must be added
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL) //Adding basic URLs
                .build();
        //3. Create instance objects of interface IService
        IService iService = retrofit.create(IService.class);
        //4. Call the method defined in the interface to get the return value
        Call<ResponseBody> call = iService.getData();
        //5. Through the Call object, synchronous or asynchronous network requests can be made.
        //5.1 Synchronization
//        try {
//            Response<ResponseBody> response = call.execute();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        //5.2 Asynchronous Mode
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.i("tag", "onResponse:" + Thread.currentThread().getName() + ":" + Thread.currentThread().getId());

                //The current TODO method runs on the main thread and updates the UI directly.
                //When the request succeeds, the response object can be obtained through the second parameter.
                try {
                    String result = response.body().string();
                    mTvResult.setText(result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                //The method of TODO's current request failure, which runs in the main thread, can update the UI directly
            }
        });
    }


    private void queryInfo() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL_QB)
                .build();
        IService iService = retrofit.create(IService.class);
        Call<ResponseBody> call = iService.getInfoData("latest", 1);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String result = response.body().string();
                    QSBean qsBean = new Gson().fromJson(result, QSBean.class);
                    mTvResult.setText(qsBean.getCount() + "");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    private void queryData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL_QB)
                .addConverterFactory(GsonConverterFactory.create()) //With Gson parser, the resulting json string is automatically converted into the corresponding bean object.
                .build();
        IService iService = retrofit.create(IService.class);
        Call<QSBean> call = iService.getBeanData("latest", 1);
        call.enqueue(new Callback<QSBean>() {
            @Override
            public void onResponse(Call<QSBean> call, Response<QSBean> response) {
                QSBean bean = response.body();
                mTvResult.setText(bean.getErr() + ":" + bean.getPage());
            }

            @Override
            public void onFailure(Call<QSBean> call, Throwable t) {

            }
        });
    }

    private void queryMapData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .build();
        IService iService = retrofit.create(IService.class);
        //limit=20&ad=2&gender=1&offset=0&generation=1
        Map<String, String> params = new HashMap<>();
        params.put("limit", "20");
        params.put("ad", "2");
        params.put("gender", "1");
        params.put("offset", "0");
        params.put("generation", "1");
        Call<ResponseBody> call = iService.getQueryData(params);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                ResponseBody responseBody = response.body();
                try {
                    String reslut = responseBody.string();
                    mTvResult.setText(reslut);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

}

PostActivity

public class PostActivity extends AppCompatActivity {

    @BindView(R.id.btn_field)
    Button mBtnField;
    @BindView(R.id.btn_field_map)
    Button mBtnFieldMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_field, R.id.btn_field_map})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_field:
                postField();
                break;
            case R.id.btn_field_map:
                postFieldMap();
                break;
        }
    }

    private void postField() {
        ////`platform=2&gifttype=1&compare=60841c5b7c69a1bbb3f06536ed685a48
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL_GIFT)
                .build();
        IService iService = retrofit.create(IService.class);
        Call<ResponseBody> call = iService.postField(2, 1, "60841c5b7c69a1bbb3f06536ed685a48");
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String result = response.body().string();
                    System.out.println(result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    private void postFieldMap(){
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL_GIFT)
                .build();
        IService iService = retrofit.create(IService.class);
        Map<String,String> params=new HashMap<>();
        params.put("platform","2");
        params.put("gifttype","1");
        params.put("compare","60841c5b7c69a1bbb3f06536ed685a48");
        Call<ResponseBody> call = iService.postFieldMap(params);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String result = response.body().string();
                    System.out.println(result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }
}

Posted by vargefaret on Thu, 28 Mar 2019 09:36:29 -0700