Android框架-Retrofit网络库

 

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添加实体类对象
@FormUrlEncodedURL编码

 

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.Gsoncom.squareup.retrofit2:converter-gson:2.0.2
2.Jacksoncom.squareup.retrofit2:converter-jackson:2.0.2
3.Simple XMLcom.squareup.retrofit2:converter-simplexml:2.0
4.Protobufcom.squareup.retrofit2:converter-protobuf:2.0.2
5.Moshicom.squareup.retrofit2:converter-moshi:2.0.2
6.Wirecom.squareup.retrofit2:converter-wire:2.0.2
7.Scalarscom.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对象

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luckyliuqs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值