Retrofit网络连接

之前初步了解了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。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值