1.什么是Retrofit 2
Retrofit 2 是square公司制作的一个Java网络请求库,可以让你的项目中的网络请求变得十分的方便和快捷。
2.代码实例
使用Retrofit2分为以下几个步骤,我将用我现在手上的一个项目作为示例进行介绍。
本项目中,我们需要向用POST请求向服务器进行登陆操作,并取得返回的数据
a.创建一个POJO
import lombok.Data;
@Data
public class LoginInform {
private String username;
private String password;
}
这里我们使用了Lombok来让代码更加简洁;这是向服务器提交登陆表单的POJO
@Data
public class UserAccount {
private String username;
private String name;
private String type;//student,teacher,admin
private String avatar;
private String gender;//male,female
private String email;
//student attribute
private int gitId;
private String number;
//teacher attribute
private String authority;
}
这是接收服务器返回数据的POJO
b.定义网络请求接口
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;
/**
* Created by mazhangchi on 2017/6/19.
*/
public interface AuthService {
@Headers({"Content-Type: application/json","Accept: application/json"})
@POST("user/auth")
Call<UserAccount> login(@Body LoginInform loginInform );
}
这里用@Header来设置请求的格式;用@POST定义请求的url;Call<T> 是Retrofit定义的返回的数据处理结构;@Body定义了请求体就是我们的loginInform对象
这里面Retrofit会自动调用GSON来将对象转化为json,同时也会将服务器返回的json转化为我们需要的UserAccount对象,十分方便
c.创建Retrofit对象
public class RetrofitHelper {
private static final String TAG = RetrofitHelper.class.getSimpleName();
private static Retrofit client;
private static AuthService authService;
private static void initClient(){
client = new Retrofit.Builder()
.baseUrl(NetConfig.URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
public static AuthService getAuthService(){
if(null == authService){
if(client == null){
initClient();
}
authService = client.create(AuthService.class);
}
return authService;
}
其中,NetConfig.URL中是项目服务器的地址,这里我就不贴出来了
d.发送请求
RetrofitHelper.getAuthService().login(loginInform)
.enqueue(new Callback<UserAccount>() {
@Override
public void onResponse(Call<UserAccount> call, Response<UserAccount> response) {
if(response.code() == 200){
//登陆成功
//设置token
String tokenOrigin = username+":"+password;
String token = Base64.encodeToString(tokenOrigin.getBytes(),Base64.DEFAULT);
ApplicationInform.setToken("Basic"+" "+token);
//设置当前用户信息
UserAccount userAccount = response.body();
ApplicationInform.setCurrentUser(userAccount);
}else{
//登陆失败
Toast.makeText(getApplicationContext(),"用户名或密码错误",Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<UserAccount> call, Throwable t) {
Toast.makeText(getApplicationContext(),"网络错误:"+t.getMessage(),Toast.LENGTH_LONG).show();
}
});
我们可以看到,Retrofit可以根据接口直接创建出对应的实现而不需要我们手动实现,十分方便。
Callback可以进行异步处理
可以看出,Retrofit可以极大简化我们项目的网络请求,并且它还可以和RxJava结合使用实现更强大的功能!