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