Retrofit是一个可以通过GET、POST、PUT、DELETE、HEAD去请求访问服务器,通过okhttp请求网络操作并把结果封装为Gson、Jsckson、Moshi、Protobuf、Wire、Simple Xml对象返回。主要操作步骤如下:
第一步:代码前的准备
1 添加网络权限 <uses-permission android:name="android.permission.INTERNET"/>
2 添加Gradle compile'com.squareup.retrofit2:retrofit:2.0.1'
Retrofit内部集成了okhttp,所以我们可以不再添加okhttp的jar
3 根据返回类型添加转换器,主要用在addConverterFactory()方法中
- Gson:
com.squareup.retrofit2:converter-gson
- Jackson:
com.squareup.retrofit2:converter-jackson
- Moshi:
com.squareup.retrofit2:converter-moshi
- Protobuf:
com.squareup.retrofit2:converter-protobuf
- Wire:
com.squareup.retrofit2:converter-wire
- Simple XML:
com.squareup.retrofit2:converter-simplexml
第二步:创建接口,其中@GET是请求方式,根据需要选取5种中任意一种。(“/api/...”)这些为请求的接口,路径注意一般Base URL以/结尾,@URL不要以/开头。当然这个不这么做也可以,重点是链接与Base URL能够顺利拼接即可。
请求参数 a: 直接设置参数方式 @GET(“user/list?sort=desc”)
b: 替换参数的请求方式 @GET ("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
c:查询参数指定 @GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
d:复杂的查询参数指定,一般采用Map
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
f:指定对象作用请求体
@POST("users/new")
Call<User> createUser(@Body User user);
还有许多就不一一介绍了,可以自行查看API http://square.github.io/retrofit/
public interface ApiService { @GET("api/userCenter/listReadHistory.do") Call<ReadTrackListRes> readTrackList(@QueryMap Map<String, String> map); //map为复杂的查询参数,Call为回调处理 }第三步: 接口处理,获取数据
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.retrofit_activity); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://。。。。。/") //Base路径,与第二步的@GET路径相拼接 .addConverterFactory(GsonConverterFactory.create()) //设置返回数据转换器,第一步中配置的Gradle与之对应 .build(); apiService = retrofit.create(ApiService.class);// map为第二步中的复杂参数,注意map必须符合接口请求规范,此处读者照搬可能读取不到需要的数据apiService.readTrackList(map).enqueue(new Callback<ReadTrackListRes>() {@Override public void onResponse(Call<ReadTrackListRes> call, Response<ReadTrackListRes> response) { Log.i("TAG","--Call:" + response.body().readTime); } @Override public void onFailure(Call<ReadTrackListRes> call, Throwable t) { } }); }
配置上面的步骤后基本可以实现通过Retrofit获取接口数据的要求,如果读者完全按上面的步骤处理是达不到想要的结果的,需要自己配置url,应为这个url为内网的,还有像ReadTrackListRes这样的实体类,读者需要自己设计。如有什么疑问欢迎下面留言,本人水平有限写的不好,勿喷谢谢。