Android Retrofit 的使用

第一步:

依赖包导入:


    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'

网络权限:

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

第二步:

创建接口设置请求类型与参数

新建UserInfoModel类和UserMgrService接口

常用参数注解:

@GET,@POST :确定请求方式

@Path:请求URL的字符替代

@Query:要传递的参数

@QueryMap:包含多个@Query注解参数

@Body:添加实体类对象

@FormUrlEncoded:URL编码

第三步:创建Retrofit对象,设置数据解析器

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(Config.MAIN_PATH)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

第四步:生成接口对象

UserMgrService userMgrService = retrofit.create(UserMgrService.class);

第五步:调用接口方法返回Call对象

Call<UserInfoModel> call = userMgrService.login("zhangsan", "123456");

第六步:发送请求(同步,异步)

同步:调用Call对象的execute(),返回结果的响应体;

异步:调用Call对象的enqueue(),参数是一个回调;

第七步:处理返回数据

接下来是代码:

Config.class
public interface Config {
    String MAIN_PATH = "http://api.XXXXXXXXXX.cn/";
}
UserInfoModel.class
public class UserInfoModel {

    public int code;
    public UserInfo data;
    public String message;

    public static class UserInfo{
        public int id;
        public String username;
        public String email;
        public String tel;
    }
}
UserMgrService.class
public interface UserMgrService {

    @GET("login.php")
    Call<UserInfoModel> login(@Query("username")String username,@Query("pwd")String pwd);

    @POST("login.php")
    @FormUrlEncoded
    Call<UserInfoModel> register(@Field("username") String username, @Field("pwd") String pwd);

}

MainActivity.class

 //创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.MAIN_PATH)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //获取UserMgrService对象
        UserMgrService userMgrService = retrofit.create(UserMgrService.class);
        //调用登录login方法
        Call<UserInfoModel> call = userMgrService.login("zhangsan", "123456");
        //发送请求
        call.enqueue(new Callback<UserInfoModel>() {
            @Override
            public void onResponse(Call<UserInfoModel> call, Response<UserInfoModel> response) {
                Log.e("MainActivity", "response.code:" + response.body().code);
            }

            @Override
            public void onFailure(Call<UserInfoModel> call, Throwable t) {
                Log.e("MainActivity", "Throwable:" + t);
            }
        });

所有内容源自慕课网视频:Retrofit网络库 感谢

猜你喜欢

转载自blog.csdn.net/try_zp_catch/article/details/81540506