Android中Retrofit2.0的简单使用

Retrofit2.0的使用方法:

一、官方地址:

   Retrofit2.0项目Github主页: https://github.com/square/retrofit

   Retrofit的官方文档 :            http://square.github.io/retrofit/

二、项目环境

   Android Studio3.0  、jdk1.8 

三、参考代码步骤

   1、在AndroidManifest.xml添加访问网络权限:

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

   2、在build.gradle中添加依赖

/**retrofit依赖*/
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
/**Gson解析依赖*/
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

   3、创建API接口。

         在retrofit中通过一个Java接口作为http请求的api接口。注:GET括号里面的是相对路径

public interface HttpInterface {
    @GET("test/getTest")
    Call<List<AdminEntity>> getCall();
}

    4、创建retrofit实例

/**创建Retrofit对象*/
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://192.168.199.219:8080/ssm/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    5、创建API接口实例

/**创建 网络请求接口 的实例*/
HttpInterface httpInterface=retrofit.create(HttpInterface.class);

     6、对网络请求进行封装

Call<List<AdminEntity>> call = httpInterface.getCall();

      7、发送网络请求获取json数据,通过Gson进行解析

call.enqueue(new Callback<List<AdminEntity>>() {
    /**请求成功时回调*/
    @Override
    public void onResponse(Call<List<AdminEntity>> call, Response<List<AdminEntity>> response) {
        /**处理返回的数据结果*/
        if(response.isSuccessful()){
            Log.e(TAG,"请求成功");
            Gson gson = new Gson();
            ArrayList<AdminEntity> list = gson.fromJson(gson.toJson(response.body()),
                    new TypeToken<List<AdminEntity>>(){}.getType());
            Log.e(TAG,list.size()+"");
        }else{
            Log.e(TAG,"请求失败");
        }
    }
    /**请求失败时回调*/
    @Override
    public void onFailure(Call<List<AdminEntity>> call, Throwable throwable) {
        Log.e(TAG,throwable.toString());
    }
});
Retrofit2.0用法介绍完毕,完整的请求地址:
http://192.168.199.219:8080/ssm/test/getTest

运行结果:


Demo源码

猜你喜欢

转载自blog.csdn.net/daxudada/article/details/79788659