Retrofit联网操作步骤,非常简单

添加Retrofit依赖

compile 'com.squareup.retrofit2:retrofit:2.4.0'

指定使用Gson解析数据,并与Retrofit关联(如果使用到)

compile 'com.google.code.gson:gson:2.8.5'

compile 'com.squareup.retrofit2:converter-gson:2.4.0'

使用步骤:

1.获取Builder对象,并使用builder对象配置基本参数

Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl("http://192.168.8.106:8080/");
builder.addConverterFactory(GsonConverterFactory.create());

2.通过builder构建Retrofit对象

Retrofit retrofit = builder.build();

3.定义一个接口配置链接和参数(封装完整url地址和请求参数、指定请求方式(GET或者POST))

public interface ResponseService {
    @GET(Constant.login)
    Call<ResponseInfo> login(@Query("sellerId") Integer id);
}

4.通过retrofit对象获得第3步定义的接口服务对象

ResponseService responseService = retrofit.create(ResponseService.class);

5.使用接口服务对象(responseService)调用接口中的方法获得Call对象,最后使用Call对象执行请求

    Call<ResponseInfo> call = responseService.login(1);
    call.enqueue(new Callback<ResponseInfo>() {
        @Override
        public void onResponse(Call<ResponseInfo> call, Response<ResponseInfo> response) {
            mMainActivity.success();
        }

        @Override
        public void onFailure(Call<ResponseInfo> call, Throwable t) {
            mMainActivity.failed();
        }
    });
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值