Retrofit简单使用方法

废话不多说了,直接说步骤,后续使用方法会继续更新。

1.配置gradle

在grald中添加

compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2' //解析数据使用

2.创建获取数据entity

public class User {
    private String name;
    private String email;
    private String id;

后面get/set方法省略

3.添加权限 

<uses-permission android:name="android.permission.INTERNET" />

4.编写获取数据接口

public interface HttpInfo {
    @GET("user/info")
    Call<User> getUserInfo(@Query("id") int id);//retrofit建议url不用/开头
}

5.获取数据

public void getUserInfo(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.138.01:8080/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    HttpInterface service = retrofit.create(HttpInterface.class);
    Call<User> call = service.getUserInfo(1);
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            User mUser= response.body();
            //Todo 获取到user信息,后续操作在这里进行
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
          
        }
    });
}
retrofit 的github地址:https://github.com/square/retrofit
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值