您的位置:首页 > 移动开发 > Android开发

Android中Retrofit2.0的简单使用

2018-04-02 15:07 411 查看
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.Buil
4000
der()
.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源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: