1.概念
1.1 介绍
Retrofit是Square公司基于RESTful风格推出的网络框架封装。
1.2 Retrofit与OkHttp的关系
Retrofit是基于OkHttp的网络请求框架的二次封装,其本质仍是OkHttp。
1.3 Retrofit库包结构
1.4 Retrofit与其他网络库的对比
1.AndroidAsynHttp 基于HTTPClient,其作者已经停止维护,Android5.0不再使用HttpClient 2.Volley 基于HttpUrlConnection,Google Docs官方推出,只适合轻量级网络交互,如数据传输小,不适合
大文件上传下载的场景。
1.5 Retrofit的优点
API设计简洁易用,注解化配置高度解耦,支持多种解析器,支持Rxjava。
1.6 常用参数注解
@Get、@POST 确定请求方式 @Path 请求URL的字符替代 @Query 要传递的参数 @QueryMap 包含多个@Query注解参数 @Body 添加实体类对象 @FormUrlEncoded URL编码
2.Retrofit的使用
2.1 第一步
添加Retrofit开源库、OkHttp网络库、数据解析器集成,注册网络权限。如下所示:
// OkHttp implementation 'com.squareup.okhttp3:okhttp:3.4.1' // retrofit compile 'com.squareup.retrofit2:retrofit:2.2.0' // retrofit converter-gson compile 'com.squareup.retrofit2:converter-gson:2.0.2'
<uses-permission android:name="android.permission.INTERNET"/>
2.2 第二步
创建接口设置请求类型与参数。
新建UserIndoModel类与UserMgrService接口,然后使用如下所示:
@GET("login") public Call<UserInfoModel> login(@Query("username") String username, @Query("password") String password);
2.2 第三步
1)创建Retrofit对象、设置数据解析器。如下所示:
Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL) .addConverterFactory(GsonConverterFactory.create()).build();
2)常用的数据解析器
如下所示:
1.Gson com.squareup.retrofit2:converter-gson:2.0.2 2.Jackson com.squareup.retrofit2:converter-jackson:2.0.2 3.Simple XML com.squareup.retrofit2:converter-simplexml:2.0 4.Protobuf com.squareup.retrofit2:converter-protobuf:2.0.2 5.Moshi com.squareup.retrofit2:converter-moshi:2.0.2 6.Wire com.squareup.retrofit2:converter-wire:2.0.2 7.Scalars com.squareup.retrofit2:converter-scalars:2.0.2 2.2 第四步
生成接口对象。如下所示:
UserMgrService service = retrofit.create(UserMgrService.class);
2.2 第五步
调用接口方法返回Call对象。如下所示:
Call<UserInfoModel> call = service.login("admin","123456");
2.2 第六步
发送请求(同步、异步)。如下所示:
同步:调用Call对象的execute(),返回结果的响应体 异步:调用Call对象的enqueue(CallBack callnack),传入的参数是一个回调
2.2 第七步
处理返回的数据。
3.使用Retrofit完成用户登录案例
3.1 创建布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="登录" android:gravity="center" android:textSize="20sp"/> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_content" android:layout_width="match_parent" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout>
3.2 处理业务
1)创建Constants类
public class Constants { public static final String BASE_URL = "http://212.50.229.215:28080/admin/login/"; }
2)创建UserIndoModel
** * 格式对应返回的数据格式 */ public class UserInfoModel { //状态码 public int code; //用户信息 public UserInfo data; //描述信息 public String mseeage; public static class UserInfo{ public int id; public String username; public String email; public String tel; } }
3)创建UserMgrService
public interface UserMgrService { @GET("login") Call<UserInfoModel> login(@Query("username") String username, @Query("password") String password); }
4)在LoginActivity.java中
public class LoginActivity extends AppCompatActivity { private Button button; private TextView contentTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); contentTextView = findViewById(R.id.tv_content); button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //1.创建Retrofit对象 Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); //2.获取UserMgrService对象 UserMgrService userMgrService = retrofit.create(UserMgrService.class); //3.调用登录login方法获得Call对象 final Call<UserInfoModel> call = userMgrService.login("张三","123456"); //4.在子线程中发送请求,从服务端获得返回的数据 new Thread(new Runnable() { @Override public void run() { try { Response response = call.execute(); //获得从服务端返回的对象 UserInfoModel userInfoModel = (UserInfoModel)response.body(); //展示Code,主线程UI更新 int code = userInfoModel.code; showCode(code); } catch (IOException e) { e.printStackTrace(); } } }).start(); } }); } /** * 在主线程中更新UI * @param code */ public void showCode(final int code){ runOnUiThread(new Runnable() { @Override public void run() { contentTextView.setText(code); } }); } }
注意:这里返回的是一个UserInfoModel对象