Details of Retrofit

Here I'm going to talk about Android's common network request library, Retrofit.
Retrofit can be regarded as an "upgraded version" of okhttp. Why? That's because its internal default is based on okhttp for encapsulation.

1. baseUlr of retrofit2 must end with / (slash),
Otherwise, an IllegalArgumentException will be thrown, so if you see that other tutorials don't end with /,
Most of them are directly copied from Retrofit 1.X.
2. Note 1 above should describe that the path in baseUrl must end with /,
Because there are some special cases that can not end with

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.1'
    compile 'com.squareup.okhttp3:okhttp:3.9.1'

Let's look at the common methods:
The following two request methods are used as an interface class

  1. GET request mode
 //Direct splicing, remember to add a question mark, as if you must bring toutiao/index
    @GET("toutiao/index?type=shehui&key=d05b58fa6901ad9bed77a1ef08bd6ccb")
    Call<GetBean> getString();
 //{name} can be understood as the path replacement block in the simplest way, which is represented by "{}", and is used with annotation @ path. In order to decouple, the parameter name=toutiao
    @GET("{name}/index?type=shehui&key=d05b58fa6901ad9bed77a1ef08bd6ccb")
    Call<GetBean> getString2(@Path("name") String name);
 //For @ GET, parameter information can be uploaded directly in the url. Then you'll react immediately. There's also a serious coupling! So @ query
    @GET("{name}/index")
    Call<GetBean> getString3(@Path("name")String name,@Query("type") String type ,@Query("key") String key);
 //Suppose I want to upload 10 parameters in the parameters? Does this mean that I want to declare 10 @ Query parameters in the method? Of course not!
    //Retrofit also takes this into consideration, so @ QueryMap is prepared for us to upload complex parameters
    @GET("{name}/index")
    Call<GetBean> getString4(@Path("name") String name, @QueryMap HashMap<String,String> hashMap);

2.Post mode

//    @POST("toutiao/index")
//    Call<ResponseBody>  getPostString(@QueryMap HashMap<String,String> map);

    //TODO uses the failed @ BODY request BODY to encapsulate the request BODY in the way of @ BODY. Retrofit encapsulates the data in the form of JSON
    @POST("toutiao/index")
    Call<PostBean> postString(@Body BodyUser user);

    //    Code can be used after using this annotation
    @FormUrlEncoded
    @POST("toutiao/index")
    Call<PostBean> postString2(@Field("type") String type, @Field("key") String key);
    // Post form submit - multiple parameters - @ FieldMa
    @FormUrlEncoded
    @POST("login")
    Call<PostBean> postString3(@FieldMap Map<String,String> params);

    //Another solution: set charset information in the request header. Therefore, this time involves adding request headers
    @Headers("Content-type:application/x-www-form-urlencoded;charset=UTF-8")
    @FormUrlEncoded
    @POST("toutiao/index")
    Call<PostBean> postString4(@Field("type") String type, @Field("key") String key);

    class BodyUser {
        private String type;
        private String key;

        public BodyUser(String type, String key) {
            this.type = type;
            this.key = key;
        }
    }

3. Operation data

package cn.bgs.retrofit;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;


import java.io.UnsupportedEncodingException;

import cn.bgs.retrofit.bean.GetBean;
import cn.bgs.retrofit.bean.PostBean;
import cn.bgs.retrofit.r.BlogService;
import cn.bgs.retrofit.r1.GitubService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit Google official details - CSDN blog http://blog.csdn.net/sw5131899/article/details/53841907
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //        initGet();
      initPost();
    }

    private void initPost()  {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://v.juhe.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        BlogService service = retrofit.create(BlogService.class);
//        Call<PostBean> call = service.postString(new BlogService.BodyUser("shehui", "d05b58fa6901ad9bed77a1ef08bd6ccb"));

                Call<PostBean> call = service.postString2("History", "d05b58fa6901ad9bed77a1ef08bd6ccb");
        //To solve the problem of Chinese code disorder, the server background does not recognize the data as a response
        //        String name =  URLEncoder.encode("Sociology","UTF-8");
        //        Call<PostBean> call = service.postString2(name, "d05b58fa6901ad9bed77a1ef08bd6ccb");

        //        Call<PostBean> call = service.postString3("Sociology", "d05b58fa6901ad9bed77a1ef08bd6ccb");
        call.enqueue(new Callback<PostBean>() {
            @Override
            public void onResponse(Call<PostBean> call, Response<PostBean> response) {
                if (response.isSuccessful()) {
                    PostBean s1 = response.body();
                    Log.e("zhoukang", "R1++" + s1.toString());
                }
            }

            @Override
            public void onFailure(Call<PostBean> call, Throwable t) {
                Log.e("zhoukang", "R1++ fail" + t.getMessage());
            }
        });

        //        HashMap<String, String> map = new HashMap<>();
        //        map.put("type", "shehui");
        //        map.put("key", "d05b58fa6901ad9bed77a1ef08bd6ccb");
        //        Call<ResponseBody> call = service.getPostString(map);
    }


    private void initGet() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://v.juhe.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GitubService service = retrofit.create(GitubService.class);
        //        Call<GetBean> call = service.getString();
        //        Call<GetBean> call = service.getString2("toutiao");
        Call<GetBean> call = service.getString3("toutiao", "shehui", "d05b58fa6901ad9bed77a1ef08bd6ccb");

        //        HashMap<String, String> map = new HashMap<>();
        //        map.put("type", "shehui");
        //        map.put("key", "d05b58fa6901ad9bed77a1ef08bd6ccb");
        //        Call<GetBean> call = service.getString4("toutiao", map);
        call.enqueue(new Callback<GetBean>() {
            @Override
            public void onResponse(Call<GetBean> call, Response<GetBean> response) {
                GetBean s1 = response.body();
                Log.e("zhoukang", "R1++" + s1.toString());
            }

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

            }
        });
    }

}

This is actually a simple use. I hope you can understand it. It's OK to deal with simple data operations.

Tags: Retrofit Android OkHttp network

Posted on Wed, 01 Apr 2020 01:57:19 -0400 by kalebaustin