对Retrofit的学习小结

来源:互联网 发布:怎么关闭mac后台程序 编辑:程序博客网 时间:2024/06/07 05:20

根据好友余震涛的blog

Android学习之网络请求库之Retrofit2

学习并总结了学习心得:

具体实现流程:

1. gradle导入所需库。

compile 'com.squareup.okhttp3:okhttp:3.2.0'compile 'com.squareup.retrofit2:retrofit:2.0.0'compile 'com.squareup.retrofit2:converter-gson:2.0.0'compile 'com.google.code.gson:gson:2.6.2'

2. 创建服务器相对的Bean对象。

3. 创建Bean相对的Retrofit接口,预留要传入的参数。

public interface PhoneService {    @GET("/apistore/mobilenumber/mobilenumber")    Call<PhoneResult> getResult(@Header("apikey") String apikey, @Query("phone") String phone);}

4. 获取服务器数据

4.1 创建Retrofit对象,传入服务器地址。
4.2 创建获取Call的接口对象,传入相对应的class。
4.3 通过接口获取Call对象,传入各种get字段(博主所说的API地址其实也是get的一个请求key)。
4.4 通过call来enqueue服务器结果。
4.5 获取成功,对所获取的response进行操作。

private void query1() {    //创建Retrofit对象,传入服务器地址    Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(BASE_URL).build();    //创建获取Call的接口对象,传入相对应的class    PhoneService phoneService = retrofit.create(PhoneService.class);    //通过接口获取Call对象,传入api地址和get的字段,多个字段则在api后加多个参数。    Call<PhoneResult> phoneResultCall = phoneService.getResult(API_KEY, et1.getText().toString());    //通过call来enqueue服务器结果    phoneResultCall.enqueue(new Callback<PhoneResult>() {        @Override        public void onResponse(Call<PhoneResult> call, Response<PhoneResult> response) {            if (response.isSuccessful()) {                //服务器结果通过body获取到。                PhoneResult phoneResult = response.body();                if (phoneResult != null) {                    PhoneResult.RetDataEntity retDataEntity = phoneResult.getRetData();                    Toast.makeText(context, retDataEntity.getCity(), Toast.LENGTH_SHORT).show();                }            }        }        @Override        public void onFailure(Call<PhoneResult> call, Throwable t) {        }    });}

另:查了源码,发现Retrofit中除了body()方法,还可以获取返回的msg、code、header等元素。用起来很灵活。


之后还需要研究研究如何用Retrofit来实现put、post等网络请求。

0 0
原创粉丝点击