Retrofit网络框架的学习:
Retrofit底层封装OkHttp与Gson等框架,且为RESTful编程风格,必须写接口进行查询代码部分:
注意点:baseUrl必须以 ‘/’ 结束,否则会抛出异常
.addConverterFactory(GsonConverterFactory.create())
将获取到的JSON数据转换为GSON数据,进而自动封装到实体类中
@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());
}
});
}
使用GsonFormat自动生成Bean类
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;
}
}
}
}
}
接口类
注意点:注解POST或GET等必须写value属性,没有则填 ‘.’ 或 ‘/’ 且POST请求必须加上 @FormUrlEncoded 注解 ,否则会抛出异常
public interface ApiService {
@FormUrlEncoded //post请求必须加上
@POST("query") //没有数据就填 . 或者 /
Call<Weather> getWeather(@FieldMap Map<String,String> map);
}
更多接口案例
/*如果想使用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);
注解名 | 注意及作用 |
---|---|
@Body | 作用于方法的参数, 使用该注解定义的参数不可为null |
@Url | 作用于方法参数,用于添加请求的接口地址 |
@Field | 作用于方法的参数, 用于发送一个表单请求用String.valueOf()把参数值转换为String,然后进行URL编码,当参数值为null值时,会自动忽略 |
@FieldMap | 作用于方法的参数, 用于发送一个表单请求,map中每一项的键和值都不能为空,否则抛出IllegalArgumentException异常 |
@FormUrlEncoded | 用于修饰Field注解和FieldMap注解,使用该注解,表示请求正文将使用表单网址编码。字段应该声明为参数,并用@Field注释或FieldMap注释。使用FormUrlEncoded注解的请求将具”application / x-www-form-urlencoded” MIME类型。字段名称和值将先进行UTF-8进行编码,再进行URI编码. |
@GET | 用于发送一个get请求,GET注解一般必须添加相对路径或绝对路径或者全路径,如果不想在GET注解后添加请求路径,则可以在方法的第一个参数中用@Url注解添加请求路径 |
@Path | 作用于方法的参数,URL路径段中替换指定的参数值。使用String.valueOf()和URL编码将值转换为字符串,使用该注解定义的参数的值不可为空,参数值默认使用URL编码 |
@POST | 用于发送一个POST请求,POST注解一般必须添加相对路径或绝对路径或者全路径,如果不想在POST注解后添加请求路径,则可以在方法的第一个参数中用@Url注解添加请求路径 |
@Query | 作用于方法的参数,用于添加查询参数,即请求参数,参数值通过String.valueOf()转换为String并进行URL编码,使用该注解定义的参数,参数值可以为空,为空时,忽略该值 |
@QueryMap | 作用于方法的参数,以map的形式添加查询参数,即请求参数,参数的键和值都通过String.valueOf()转换为String格式,map的键和值默认进行URL编码,map中每一项的键和值都不能为空 |
成功获取数据