Android uses Retrofit web framework

Learning of Retrofit network framework:

The bottom layer of Retrofit encapsulates frameworks such as OkHttp and Gson, and it is a RESTful programming style. You must write an interface for query

Code part:

Note: baseUrl must end with'/', otherwise an exception will be thrown

.addConverterFactory(GsonConverterFactory.create())
converts the acquired JSON data into GSON data, and then automatically encapsulates it into the entity class


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
 Retrofit builder =new Retrofit.Builder()
 				/*必须以  '/'  结束*/
                .baseUrl("http://apis.juhe.cn/simpleWeather/") 
                /*将返回的数据转换为Gson*/
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiService apiService = builder.create(ApiService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("city","北京");
        map.put("key","88888888");
        apiService.getWeather(map)
                .enqueue(new Callback<Weather>() {
    
    
                    @Override
                    public void onResponse(Call<Weather> call, Response<Weather> response) {
    
    
                        try {
    
    
                            text.setText(response.body().toString());
                            Log.e("onSuccess", response.body().toString() + "");
                        } catch (Exception e) {
    
    
                            Log.e("onResponse", "获取数据错误:" + e.getMessage() );
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<Weather> call, Throwable t) {
    
    
                        Log.e("onResponse", "错误"  + t.getMessage());

                    }
                });
                }

Use GsonFormat to automatically generate Bean classes
package com.gsonweathertest.pojo;


import java.util.List;

public class Weather {
    
    

    @Override
    public String toString() {
    
    
        return "Weather{" +
                "reason='" + reason + '\'' +
                ", result=" + result +
                ", error_code=" + error_code +
                '}';
    }

    /**
     * reason : 查询成功
     * result : {"city":"苏州","realtime":{"temperature":"4","humidity":"82","info":"阴","wid":"02","direct":"西北风","power":"3级","aqi":"80"},"future":[{"date":"2019-02-22","temperature":"1/7℃","weather":"小雨转多云","wid":{"day":"07","night":"01"},"direct":"北风转西北风"},{"date":"2019-02-23","temperature":"2/11℃","weather":"多云转阴","wid":{"day":"01","night":"02"},"direct":"北风转东北风"},{"date":"2019-02-24","temperature":"6/12℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"东北风转北风"},{"date":"2019-02-25","temperature":"5/12℃","weather":"小雨转多云","wid":{"day":"07","night":"01"},"direct":"东北风"},{"date":"2019-02-26","temperature":"5/11℃","weather":"多云转小雨","wid":{"day":"01","night":"07"},"direct":"东北风"}]}
     * error_code : 0
     */

    private String reason;
    private ResultBean result;
    private int error_code;

    public String getReason() {
    
    
        return reason;
    }

    public void setReason(String reason) {
    
    
        this.reason = reason;
    }

    public ResultBean getResult() {
    
    
        return result;
    }

    public void setResult(ResultBean result) {
    
    
        this.result = result;
    }

    public int getError_code() {
    
    
        return error_code;
    }

    public void setError_code(int error_code) {
    
    
        this.error_code = error_code;
    }

    public static class ResultBean {
    
    
        @Override
        public String toString() {
    
    
            return "ResultBean{" +
                    "city='" + city + '\'' +
                    ", realtime=" + realtime +
                    ", future=" + future +
                    '}';
        }

        /**
         * city : 苏州
         * realtime : {"temperature":"4","humidity":"82","info":"阴","wid":"02","direct":"西北风","power":"3级","aqi":"80"}
         * future : [{"date":"2019-02-22","temperature":"1/7℃","weather":"小雨转多云","wid":{"day":"07","night":"01"},"direct":"北风转西北风"},{"date":"2019-02-23","temperature":"2/11℃","weather":"多云转阴","wid":{"day":"01","night":"02"},"direct":"北风转东北风"},{"date":"2019-02-24","temperature":"6/12℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"东北风转北风"},{"date":"2019-02-25","temperature":"5/12℃","weather":"小雨转多云","wid":{"day":"07","night":"01"},"direct":"东北风"},{"date":"2019-02-26","temperature":"5/11℃","weather":"多云转小雨","wid":{"day":"01","night":"07"},"direct":"东北风"}]
         */

        private String city;
        private RealtimeBean realtime;
        private List<FutureBean> future;

        public String getCity() {
    
    
            return city;
        }

        public void setCity(String city) {
    
    
            this.city = city;
        }

        public RealtimeBean getRealtime() {
    
    
            return realtime;
        }

        public void setRealtime(RealtimeBean realtime) {
    
    
            this.realtime = realtime;
        }

        public List<FutureBean> getFuture() {
    
    
            return future;
        }

        public void setFuture(List<FutureBean> future) {
    
    
            this.future = future;
        }

        public static class RealtimeBean {
    
    
            /**
             * temperature : 4
             * humidity : 82
             * info : 阴
             * wid : 02
             * direct : 西北风
             * power : 3级
             * aqi : 80
             */

            private String temperature;
            private String humidity;
            private String info;
            private String wid;
            private String direct;
            private String power;
            private String aqi;

            public String getTemperature() {
    
    
                return temperature;
            }

            public void setTemperature(String temperature) {
    
    
                this.temperature = temperature;
            }

            public String getHumidity() {
    
    
                return humidity;
            }

            public void setHumidity(String humidity) {
    
    
                this.humidity = humidity;
            }

            public String getInfo() {
    
    
                return info;
            }

            public void setInfo(String info) {
    
    
                this.info = info;
            }

            public String getWid() {
    
    
                return wid;
            }

            public void setWid(String wid) {
    
    
                this.wid = wid;
            }

            public String getDirect() {
    
    
                return direct;
            }

            public void setDirect(String direct) {
    
    
                this.direct = direct;
            }

            public String getPower() {
    
    
                return power;
            }

            public void setPower(String power) {
    
    
                this.power = power;
            }

            public String getAqi() {
    
    
                return aqi;
            }

            public void setAqi(String aqi) {
    
    
                this.aqi = aqi;
            }
        }

        public static class FutureBean {
    
    
            @Override
            public String toString() {
    
    
                return "FutureBean{" +
                        "date='" + date + '\'' +
                        ", temperature='" + temperature + '\'' +
                        ", weather='" + weather + '\'' +
                        ", wid=" + wid +
                        ", direct='" + direct + '\'' +
                        '}';
            }

            /**
             * date : 2019-02-22
             * temperature : 1/7℃
             * weather : 小雨转多云
             * wid : {"day":"07","night":"01"}
             * direct : 北风转西北风
             */

            private String date;
            private String temperature;
            private String weather;
            private WidBean wid;
            private String direct;

            public String getDate() {
    
    
                return date;
            }

            public void setDate(String date) {
    
    
                this.date = date;
            }

            public String getTemperature() {
    
    
                return temperature;
            }

            public void setTemperature(String temperature) {
    
    
                this.temperature = temperature;
            }

            public String getWeather() {
    
    
                return weather;
            }

            public void setWeather(String weather) {
    
    
                this.weather = weather;
            }

            public WidBean getWid() {
    
    
                return wid;
            }

            public void setWid(WidBean wid) {
    
    
                this.wid = wid;
            }

            public String getDirect() {
    
    
                return direct;
            }

            public void setDirect(String direct) {
    
    
                this.direct = direct;
            }

            public static class WidBean {
    
    
                @Override
                public String toString() {
    
    
                    return "WidBean{" +
                            "day='" + day + '\'' +
                            ", night='" + night + '\'' +
                            '}';
                }

                /**
                 * day : 07
                 * night : 01
                 */

                private String day;
                private String night;

                public String getDay() {
    
    
                    return day;
                }

                public void setDay(String day) {
    
    
                    this.day = day;
                }

                public String getNight() {
    
    
                    return night;
                }

                public void setNight(String night) {
    
    
                    this.night = night;
                }
            }
        }
    }
}


Interface class

Note: For annotations such as POST or GET, the value attribute must be written, if not, fill in'.' or'/' and the POST request must be annotated with @FormUrlEncoded , otherwise an exception will be thrown

public interface ApiService {
    
    
    @FormUrlEncoded  //post请求必须加上
    @POST("query") //没有数据就填 . 或者 /
    Call<Weather> getWeather(@FieldMap Map<String,String> map);

}

More interface cases

/*如果想使用url上的参数时,请求参数必须使用@Path注解来获取。*/
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);

/*还可以添加查询参数。*/
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

/*对于复杂的查询参数组合,可以使用Map。*/
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

/*@Field注解将每一个请求参数都存放至请求体中*/
/*对于复杂的查询参数组合,可以使用映射。可以通过@Body注释指定一个对象作为HTTP请求体使用。*/
@POST("users/new")
Call<User> createUser(@Body User user);

/*当@ formurlencodes出现在方法上时,将发送表单编码的数据。每个键-值对都用@Field注释,其中包含名称和提供值的对象。*/
@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

Annotation name Attention and effect
@Body Acting on the parameters of the method, the parameters defined using this annotation cannot be null
@Url Act on method parameters, used to add the requested interface address
@Field The parameters acting on the method are used to send a form request. Use String.valueOf() to convert the parameter value to String, and then perform URL encoding. When the parameter value is a null value, it will be automatically ignored
@FieldMap The parameters acting on the method are used to send a form request. The key and value of each item in the map cannot be empty, otherwise an IllegalArgumentException will be thrown
@FormUrlEncoded Used to modify Field annotations and FieldMap annotations. Using this annotation means that the request body will use the form URL encoding. Fields should be declared as parameters and annotated with @Field or FieldMap. Requests annotated with FormUrlEncoded will have the MIME type "application / x-www-form-urlencoded". The field names and values ​​will be UTF-8 encoded first, and then URI encoded.
@GET Used to send a get request, GET annotations generally must add a relative path or absolute path or full path. If you don't want to add the request path after the GET annotation, you can add the request path with the @Url annotation in the first parameter of the method
@Path Acting on the parameters of the method, replace the specified parameter value in the URL path segment. Use String.valueOf() and URL encoding to convert the value to a string. The value of the parameter defined using this annotation cannot be empty, and the parameter value uses URL encoding by default
@POST It is used to send a POST request. POST annotations generally must add a relative path or an absolute path or a full path. If you do not want to add the request path after the POST annotation, you can add the request path with the @Url annotation in the first parameter of the method
@Query The parameters acting on the method are used to add query parameters, that is, request parameters. The parameter value is converted to String through String.valueOf() and URL-encoded. Using the parameter defined by this annotation, the parameter value can be empty. If it is empty, ignore it. The value
@QueryMap Acting on the parameters of the method, add query parameters in the form of a map, that is, request parameters. The keys and values ​​of the parameters are converted to String format through String.valueOf(). The keys and values ​​of the map are URL-encoded by default, and each item in the map is Neither the key nor the value can be empty

Get data successfully
Insert picture description here

Guess you like

Origin blog.csdn.net/Android_Cob/article/details/108652824