android フレームワーク - Retrofit2 - ネットワーク リクエスト フレームワーク

Retrofit2 ネットワーク リクエスト フレームワークの簡単な使用

一般的な手順:

ステップ 1: Retrofit ライブラリの依存関係を追加する
ステップ 2: サーバーから返されるデータを受け取るクラスを作成する
ステップ 3: ネットワーク リクエストを記述するためのインターフェイスを作成する
ステップ 4: Retrofit インスタンスを作成する ステップ 5
: ネットワーク リクエスト インターフェイス インスタンスを作成して設定するネットワーク リクエスト パラメータ
ステップ 6: データ変換とスレッド切り替えの操作をカプセル化するネットワーク リクエスト (非同期/同期) を送信します。
ステップ 7: サーバーから返されたデータを処理します。

例:

ステップ 1: Retrofit ライブラリの依存関係を追加する

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

ステップ 2: サーバーから返されたデータを受け取るクラスを作成する

ここでは Hefeng Weather の都市検索 API を例に挙げます。

  1. 返されたデータを表示する
{
  "HeWeather6": [
    {
      "basic": [
        {
          "cid": "CN101281002",
          "location": "吴川",
          "parent_city": "湛江",
          "admin_area": "广东",
          "cnty": "中国",
          "lat": "21.42845345",
          "lon": "110.78050995",
          "tz": "+8.00",
          "type": "city"
        }
      ],
      "status": "ok"
    }
  ]
}
  1. サーバーから返されたデータを受け取るクラスを AS に作成します。
    新しいクラスを作成した後、編集インターフェイスで Alt+Insert を押して GsonFromat を選択するか、Alt+S ショートカット キーを直接押して、ポップアップに json 形式でデータを貼り付けます。ボックスにチェックを入れ、「ok」を押すと自動的に json が生成されます。 データ処理クラス。

ここに画像の説明を挿入
ここに画像の説明を挿入

//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;
            }
        }
    }
}

ステップ 3: ネットワークリクエストを記述するためのインターフェースを作成する

パラメータはアノテーションの形式である必要があり、Retrofit インスタンス + @GET アノテーションのフィールド + @Query パラメータ設定 (URL の後のパラメータとして) を作成することで設定された完全な Url = BaseUrl である必要があります。

//此处要请求的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);
}

ステップ 4: Retrofit インスタンスを作成する

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

ステップ 5: ネットワーク リクエスト インターフェイス インスタンスを作成し、ネットワーク リクエスト パラメータを構成する

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

ステップ 6: データ変換とスレッド切り替えの操作をカプセル化するネットワーク リクエスト (非同期/同期) を送信します。

//实例使用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();

ステップ 7: サーバーから返されたデータを処理する

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

拡張情報

おすすめ

転載: blog.csdn.net/weixin_44565784/article/details/100025891