android framework - Retrofit2 - network request framework

Simple use of Retrofit2 network request framework

Common steps:

Step 1: Add dependencies of the Retrofit library
Step 2: Create a class that receives data returned by the server
Step 3: Create an interface for describing network requests
Step 4: Create a Retrofit instance
Step 5: Create a network request interface instance and configure network request parameters
Step 6 : Send a network request (asynchronous/synchronous), which encapsulates the operations of data conversion and thread switching
Step 7: Process the data returned by the server

Example:

Step 1: Add the dependencies of the Retrofit library

implementation 'com.squareup.retrofit2:retrofit:2.6.1'
//实例用到Gson解析,所以要添加此解析器依赖库
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

Step 2: Create a class that receives the data returned by the server

Here we take Hefeng Weather's city search API as an example.

  1. view returned data
{
  "HeWeather6": [
    {
      "basic": [
        {
          "cid": "CN101281002",
          "location": "吴川",
          "parent_city": "湛江",
          "admin_area": "广东",
          "cnty": "中国",
          "lat": "21.42845345",
          "lon": "110.78050995",
          "tz": "+8.00",
          "type": "city"
        }
      ],
      "status": "ok"
    }
  ]
}
  1. Create a class in AS that receives the data returned by the server.
    After creating a new class, press Alt+Insert to select GsonFromat in the editing interface or directly press Alt+S shortcut keys, paste the data in json format in the pop-up box, and automatically generate json after pressing 'ok' Data processing class.

insert image description here
insert image description here

//City.java
public class City {
    private List<HeWeather6Bean> HeWeather6;
    public List<HeWeather6Bean> getHeWeather6() {
        return HeWeather6;
    }
    public void setHeWeather6(List<HeWeather6Bean> HeWeather6) {
        this.HeWeather6 = HeWeather6;
    }
    public static class HeWeather6Bean {
        /**
         * basic : [{"cid":"CN101281002","location":"吴川","parent_city":"湛江","admin_area":"广东","cnty":"中国","lat":"21.42845345","lon":"110.78050995","tz":"+8.00","type":"city"}]
         * status : ok
         */
        private String status;
        private List<BasicBean> basic;
        public String getStatus() {
            return status;
        }
        public void setStatus(String status) {
            this.status = status;
        }
        public List<BasicBean> getBasic() {
            return basic;
        }
        public void setBasic(List<BasicBean> basic) {
            this.basic = basic;
        }
        public static class BasicBean {
            /**
             * cid : CN101281002
             * location : 吴川
             * parent_city : 湛江
             * admin_area : 广东
             * cnty : 中国
             * lat : 21.42845345
             * lon : 110.78050995
             * tz : +8.00
             * type : city
             */
            private String cid;
            private String location;
            private String parent_city;
            private String admin_area;
            private String cnty;
            private String lat;
            private String lon;
            private String tz;
            private String type;
            public String getCid() {
                return cid;
            }
            public void setCid(String cid) {
                this.cid = cid;
            }
            public String getLocation() {
                return location;
            }
            public void setLocation(String location) {
                this.location = location;
            }
            public String getParent_city() {
                return parent_city;
            }
            public void setParent_city(String parent_city) {
                this.parent_city = parent_city;
            }
            public String getAdmin_area() {
                return admin_area;
            }
            public void setAdmin_area(String admin_area) {
                this.admin_area = admin_area;
            }
            public String getCnty() {
                return cnty;
            }
            public void setCnty(String cnty) {
                this.cnty = cnty;
            }
            public String getLat() {
                return lat;
            }
            public void setLat(String lat) {
                this.lat = lat;
            }

            public String getLon() {
                return lon;
            }
            public void setLon(String lon) {
                this.lon = lon;
            }
            public String getTz() {
                return tz;
            }
            public void setTz(String tz) {
                this.tz = tz;
            }
            public String getType() {
                return type;
            }
            public void setType(String type) {
                this.type = type;
            }
        }
    }
}

Step 3: Create an interface for describing network requests

Parameters must be in the form of annotations, complete Url = baseUrl set by creating a Retrofit instance + fields in the @GET annotation + @Query parameter settings (serve as parameters in the url?)

//此处要请求的Url为:https://search.heweather.net/find?location=CN101281002&key=5126356**可自行去和风官网申请key**7286
//baseUrl:https://search.heweather.net/
//@GET:find
//@Query:请求参数,即?后面的参数,@Query("键名")  键值的类型  形参
public interface GetCity_Interface {
	//用GET方式发送请求
    @GET("find")
     其中返回类型为Call<*>,*是接收数据的类(即上面定义的City类)
    // 如果想直接获得Responsebody中的内容,可以定义网络请求返回值为Call<ResponseBody>
    public Call<City> getCall(@Query("mode") String mode,
                              @Query("location") String location,
                              @Query("key") String key);
}

Step 4: Create a Retrofit instance

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://search.heweather.net/")	//设置(部分)Url
                .addConverterFactory(GsonConverterFactory.create())	//设置解析器,这里用Gson解析器
                .build();
//可拓展 addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平台

Step 5: Create a network request interface instance and configure network request parameters

//创建 网络请求接口实例,create(刚创建的网络接口)
GetCity_Interface getCity_interface = retrofit.create(GetCity_Interface.class);
//配置网络请求参数,调用接口定义的getCall()方法
Call<City> call = getCity_interface.getCall(mode[0], cityName, "5126356**可自行去和风官网申请key**7286");

Step 6: Send a network request (asynchronous/synchronous), which encapsulates the operations of data conversion and thread switching

//实例使用enqueue异步请求
call.enqueue(new Callback<City>() {
            @Override
            public void onResponse(Call<City> call, Response<City> response) {
            	//请求成功做相应操作
                cities = response.body().getHeWeather6().get(0).getBasic();
                //此处结合了先前自定义的ListView对返回的数据用列表显示出来
                //文章:https://blog.csdn.net/weixin_44565784/article/details/100023739
                CityAdater cityAdater = new CityAdater(SearchCity.this, R.layout.city_list_item, cities);
                cityListV.setAdapter(cityAdater);
            }

            @Override
            public void onFailure(Call<City> call, Throwable t) {
            	//请求失败
                t.printStackTrace();
            }
        });
// 发送网络请求(同步)
// Response<Reception> response = call.execute();
// 对返回数据进行处理
// response.body().show();

Step 7: Process the data returned by the server

//即步骤六的 请求成功做相应操作
cities = response.body().getHeWeather6().get(0).getBasic();
 //此处结合了先前自定义的ListView对返回的数据用列表显示出来
CityAdater cityAdater = new CityAdater(SearchCity.this, R.layout.city_list_item, cities);
cityListV.setAdapter(cityAdater);

Extended information

Guess you like

Origin blog.csdn.net/weixin_44565784/article/details/100025891