1.添加依赖
app/build.gradle文件中dependencies
标签下,添加:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
2.接口API
网络接口用的是和风天气的免费接口
定义接口
public interface ApiService {
//url实例:https://free-api.heweather.com/v5/weather?city=yourcity&key=yourkey
//正常的网络请求api,@Query参数会直接显示在url里
@GET("weather")
Call<ResponseBody> getWeather(@Query("city") String city, @Query("key") String key);
}
3.异步调用接口
//自己注册后的key
private static final String KEY = "124***fasdf****dcf*****3";
//创建Retrofit对象,设置baseUrl,Retrofit2.0的baseurl需要`/`结尾
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://free-api.heweather.com/v5/")
.build();
//接口调用api,传入查询的参数
ApiService apiService = retrofit.create(ApiService.class);
Call<ResponseBody> call = apiService.getWeather("上海", KEY);
//同步用call.execute();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.i("test", "result = \n" + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("test", "onFailure");
}
});
//请求移除用call.cancel();
4.@Path和@Query
2中使用的是@Query
,直接显示在url的查询条件,还可以通过变量控制url路径的@Path
使用@Path
//url中的变量用{}包括,并且与@Paht中声明的值相同
@GET("{user_name}/article/details/{blog_id}")
Call<ResponseBody> getBLog(@Path("user_name") String userName, @Path("blog_id") String blogId);
5.POST方式提交,用@Body 包装表单数据类
首先要添加转化Gson的支持,可直接将@Body 表示的类封装成json数据。添加依赖:
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
接着为retrofit
添加转换工厂
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://xxxx.xxxx.com/user/")
//添加Gson转换
.addConverterFactory(GsonConverterFactory.create())
.build();
接口api
比如某个登录接口
//注意是POST格式才能用@Body
@POST("login")
Call<ResponseBody> loginByBean(@Body LoginUser user);
定义的LoginUser
public class LoginUser {
//用@SerializedName() 可以指明json转换时候的字段名字
@SerializedName("name")
private String user_name;
@SerializedName("password")
private String user_password;
@SerializedName("check")
private String checkCode;
public LoginUser(String user_name, String user_password, String checkCode) {
this.user_name = user_name;
this.user_password = user_password;
this.checkCode = checkCode;
}
//setter and getter
...
}
异步调用发起请求
//直接传入LoginUser对象
apiService.loginByBean(new LoginUser("jack", "123123", "asdf"))
.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.i("test", "by body ,result = \n" + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("test", "onFailure");
}
});
添加gons转换后,还可以直接将返回的结果类型变为需要的类型。
api接口
//泛型直接指定为Weather
@GET("weather")
Call<Weather> getWeatherToWeatherBean(@Query("city") String city, @Query("key") String key);
创建Weather类,可使用AndroidStudio
插件GsonFormat
快速将json数据准换成java类。
最后调用
Call<Weather> call = apiService.getWeatherToWeatherBean("上海", KEY);
call.enqueue(new Callback<Weather>() {
@Override
public void onResponse(Call<Weather> call, Response<Weather> response) {
//可以直接.getHeWeather5()然后调用类成员
Log.i("test", "to weather bean : " + response.body()
.getHeWeather5().get(0).getAqi().toString());
}
@Override
public void onFailure(Call<Weather> call, Throwable t) {
}
});
6.添加CallAdapter工厂,使用RxJava
添加依赖:
compile 'io.reactivex.rxjava2:rxjava:2.1.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
然后给retrofit添加Rxjava工厂
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://free-api.heweather.com/v5/")
//gons转换工厂
.addConverterFactory(GsonConverterFactory.create())
//rxjava-calladapter工厂
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
API接口更改:
//注意 Call换成了OBservable被观察者
@GET("weather")
Observable<Weather> getWeatherByRxjava(@Query("city") String city, @Query("key") String key);
最后调用
Observable<Weather> call = apiService.getWeatherByRxjava("上海", KEY);
//异步网络访问,在io线程(子线程)
call.subscribeOn(Schedulers.io())
//回到主线程更新UI
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Weather>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.i("test", "onSubscribe");
}
@Override
public void onNext(@NonNull Weather weather) {
Log.i("test", "rxjava result = " + weather.getHeWeather5()
.get(0).getAqi().toString());
}
@Override
public void onError(@NonNull Throwable e) {
Log.i("test", "onError");
}
@Override
public void onComplete() {
Log.i("test", "onComplete");
}
});
7.打印请求地址和返回内容
使用Retrofit
网络请求,需要使用到HttpLoggingInterceptor
类,首先要添加依赖:
compile 'com.squareup.okhttp3:logging-interceptor:3.8.1'
然后初始化HttpLoggingInterceptor
类:
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
//打印retrofit日志
Log.i("test", "back = " + message);
}
});
//设置打印的等级
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
打印的等级有:NONE、BASIC、HEADERS、BODY
接着配置okhttp
的client:
OkHttpClient client = new OkHttpClient.Builder()
//加入打印类loggingInterceptor
.addInterceptor(loggingInterceptor)
.connectTimeout(2000, TimeUnit.SECONDS)
.readTimeout(2000, TimeUnit.SECONDS)
.writeTimeout(2000, TimeUnit.SECONDS)
.build();
最后创建Retrofit
的时候配置进去:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://free-api.heweather.com/v5/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//将定义的okhttp配置进入retrofit中
.client(client)
.build();