Retrofit2.0基础用法

来源:互联网 发布:马赛克拼图软件 编辑:程序博客网 时间:2024/04/30 20:59

1.导包

//定义版本号def retrofit_version = "2.1.0"def rxjava_version = "2.0.1"dependencies {    //RxJava的依赖包    compile 'io.reactivex.rxjava2:rxjava:'+rxjava_version    //RxAndroid的依赖包    compile 'io.reactivex.rxjava2:rxandroid:'+rxjava_version    //Rxjava+Retrofit 用到的 一个 依赖, 使接口回调的数据 以Rxjava形式 供我们接受    compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0-RC3'    //Retrofit 的依赖包    compile 'com.squareup.retrofit2:retrofit:'+retrofit_version    //自动将服务器返回的数据 以及 我们传给一个JavaBean 实体,转换成json。    compile 'com.squareup.retrofit2:converter-gson:'+retrofit_version    //gson 实体解析库    compile 'com.google.code.gson:gson:2.7'    //okhttp 日志拦截器    compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'}

2.注解介绍

1.常见的get

Retrofit retrofit = new Retrofit.Builder()    .baseUrl("https://api.github.com/")//传入域名    .build();public interface GitHubService {    //无参数    @GET("users/stven0king/repos")    Call<List<Repo>> listRepos();    //使用@path   @GET("users/{user}/repos")   Call<List<Repo>> listRepos(@Path("user") String user);    //少数参数    @GET("users/stven0king/repos")    Call<List<Repo>> listRepos(@Query("time") long time);    //参数较多    @GET("users/stven0king/repos")    Call<List<Repo>> listRepos(@QueryMap Map<String, String> params);}

@Query和@QueryMap也可以结合在一起使用。
要是对应的url在服务端支持get/post两种类型的请求的话,那么上面的@GET变为@POST也可以执行,只不过post请求时所带的参数也会像get方式一样已?key=value&key1=vaule2…的形式拼接在url的后边。

2.常见的post

Retrofit retrofit = new Retrofit.Builder()    .baseUrl("https://api.github.com/")    .build()public interface GitHubService {    //无参数    @POST("users/stven0king/repos")    Call<List<Repo>> listRepos();    //少数参数    @FormUrlEncoded    @POST("users/stven0king/repos")    Call<List<Repo>> listRepos(@Field("time") long time);    //参数较多    @FormUrlEncoded    @POST("users/stven0king/repos")    Call<List<Repo>> listRepos(@FieldMap Map<String, String> params);}

@FromUrlEncoded和@Field或者@FieldMap 表示表单提交的方式

@Field和@FieldMap可以结合在一起使用。

另外是不是发现了比起@GET多了一个@FromUrlEncoded的注解。如果去掉@FromUrlEncoded在post请求中使用@Field和@FieldMap,那么程序会抛出Java.lang.IllegalArgumentException: @Field parameters can only be used with form encoding. (parameter #1)的错误异常。如果将@FromUrlEncoded添加在@GET上面呢,同样的也会抛出java.lang.IllegalArgumentException:FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).的错误异常。

3.@url

Retrofit retrofit = new Retrofit.Builder()    .baseUrl("https://api.github.com/")    .build()public interface GitHubService {  @GET  Call<List<Repo>> listRepos(@Url String user);}

当@GET或@POST注解的url为全路径时(可能和baseUrl不是一个域),会直接使用注解的url的域。
如果请求为post实现,那么最好传递参数时使用@Field、@FieldMap和@FormUrlEncoded。因为@Query和或QueryMap都是将参数拼接在url后面的,而@Field或@FieldMap传递的参数时放在请求体的。
使用@Path时,path对应的路径不能包含”/”,否则会将其转化为%2F。在遇到想动态的拼接多节url时,还是使用@Url吧。

4.@Part,@PartMap
用于POST文件上传

@Multipart和@Part或者@PartMap是成对出现的

  @Multipart    @POST("upload")    Call<ResponseBody> upload(@Part("description") RequestBody description,                              @Part MultipartBody.Part file); RequestBody requestFile =            RequestBody.create(MediaType.parse("multipart/form-data"), file);

5.@Header和@Headers

@Header:header处理,不能被互相覆盖,用于修饰参数,

//动态设置Header值@GET("user")Call<User> getUser(@Header("Authorization") String authorization)

等同于 :

//静态设置Header值@Headers("Authorization: authorization")//这里authorization就是上面方法里传进来变量的值@GET("widget/list")Call<User> getUser()

@Headers 用于修饰方法,用于设置多个Header值:

@Headers({    "Accept: application/vnd.github.v3.full+json",    "User-Agent: Retrofit-Sample-App"})@GET("users/{username}")Call<User> getUser(@Path("username") String username);

最后本人封装好一个工具类Retrofit2.0+Rxjava2.0使访问网络更简单
地址 :

https://github.com/Abounce/RetrofitUtils 框架

0 0
原创粉丝点击