之前初步了解了Rx的简单实用和原理。
这次一起学习retrofit2。其底层是Okhttp。其中需要的jar及其依赖包可通过。https://jcenter.bintray.com/com/squareup/该网址进行下载。
1、配置文件添加依赖
2、注册网络权限
3、布局文件
<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Retrofit" android:onClick="btnClick"/>
4、创建业务接口
public interface ApiService{ @GET("login.do") Call<BaseResponse<List<UserModel>>> getUsers(); }
5、大多数调用返回的数据类型多为code msg data类型。定义json数据基类。
public class BaseResponse<T> implements Serializable{ @SerializedName("code") public int code; @SerializedName("msg") public String msg; @SerializedName("data") public T data; }6、定义model数据类型,接收到的返回数据的数据bean。
public class UserModel implements Serializable { public String username; public String password; @Override public String toString() { return "UserModel{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }7、主体mainactivity中使用。创建retrofit实例并完成配置以及使用call实例完成异步请求。
public void btnClick(View view) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseurl) .addConverterFactory(GsonConverterFactory.create()) .build(); ApiService apiService = retrofit.create(ApiService.class); apiService.getUsers().enqueue(new Callback<BaseResponse<List<UserModel>>>() { @Override public void onResponse(Call<BaseResponse<List<UserModel>>> call, Response<BaseResponse<List<UserModel>>> response) { showToast("成功:" + response.body().data.toString()); Log.e(TAG, "成功:" + response.body().data.toString()); Log.e(TAG, "retCode:" + response.code() + ",msg:" + response.message()); mTextView.setText("成功:" + response.body().data.toString()); } @Override public void onFailure(Call<BaseResponse<List<UserModel>>> call, Throwable t) { showToast("失败:" + t.getMessage()); Log.e(TAG, "失败:" + t.getMessage()); mTextView.setText("失败:" + t.getMessage()); } }); }
GsonConverterFactory
这个可用其他解析方式代替如fastjson,但是要自定义ConvertFactory。