Retrofit初体验,复杂数据gson解析

来源:互联网 发布:用网络看电视直播 编辑:程序博客网 时间:2024/04/30 12:48

本人之前一直用的volley之类的框架,最近看到retrofit+rxAndroid非常火,所以试着了解下。
因为之前对OKHttp也不熟,所以整个流程对我来说极其陌生。

参考过这篇文章,感谢。
但也因为这篇文章踩入另一个坑。

OK,让我们一步步的来。这里只讲retrofit,后期会加上rxAndroid.
首先:导包

    compile 'com.squareup.retrofit2:retrofit:2.0.2'    compile 'com.squareup.retrofit2:converter-gson:2.0.2'    compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'    compile 'com.squareup.okhttp3:okhttp:3.0.1'

第三个跟第四个是为了添加拦截器导入的。

首先定义一个interface

public interface ApiService {    @GET("getList")    Call<TestModel> getModel(@Query("fieldId") int fieldId, @Query("equipmentId") int equipmentId);    }

如上图所示,最后的网址实际上为:http://baseUrl+getList?fieldId=0&equipmentId=0
其中的baseUrl自己定义,并且在retrofit2.0之后,baseurl后面要带“/”号,比如:http://www.baidu.com/
TestModel是自己定义的json串的javabean。 getModel是方法名字。

另外还有一些带参的写法。

    @GET("/users/{username}")    Call<User> getUser(@Path("username") String username);    @GET("/group/{id}/users")    Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);    @POST("/users/new")    Call<User> createUser(@Body User user);   /*如果你要提交多参数表单数据(multi-part form data),可以使用@Multipart与@Part注解:*/    @Multipart    @POST("/some/endpoint")    Call<SomeResponse> someEndpoint(@Part("name1") String name1, @Part("name2") String name2)    /*如果我们希望提交 form-encoded name/value ,我们可以使用@FormUrlEncoded 与 @FieldMap注解:*/   @FormUrlEncoded   @POST("/some/endpoint")   Call<SomeResponse> someEndpoint(@FieldMap Map<String, String> names);

retrofit的网络请求比较简单,代码看起来比较简洁,据说速度也比较快。

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

如果要添加拦截器,先初始化:

 HttpLoggingInterceptor http=new HttpLoggingInterceptor(); http.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(http).build(); Retrofit retrofit=new Retrofit.Builder()                               .baseUrl(BASEURL)                               .addConverterFactory(GsonConverterFactory.create())                               .client(client)                               .build();

添加拦截器会在logcat中打印出请求header、访问的网址,返回的code和所有数据。
retrofit在2.0后可以在返回直接获取到url。

 ApiService apiService = retrofit.create(ApiService.class); Call<TestModel> call=apiService.getModel(Int xxx,Int  xxx); call.enqueue(new Callback<TestModel>() {      @Override      public void onResponse(Call<TestModel> call, Response<TestModel> response) {         Log.e(TAG,"成功");      }      @Override      public void onFailure(Call<TestModel> call, Throwable t) {      }  });

也可以在onResponse方法里面直接调用call.request().url();拿到请求的url。
enqueue是异步调用。同步可以直接调用call.execute();

由于本人用的是公司项目的接口,就不提供源码了,有问题可以一起讨论。

0 0