retrofit之基本内容

介绍
Retrofit将网络请求API转换为一个Java 接口。

public interface MovieService {
@GET("top250")
Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
}
Retrofit生成一个MovieService的接口实现。

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.douban.com/v2/movie/")
.addConverterFactory(GsonConverterFactory.create())
.build();

MovieService movieService = retrofit.create(MovieService.class);
MovieService可以创建一个同步或者异步的远程服务器请求:Call。

Call<MovieEntity> topMovie = movieService.getTopMovie(0, 1);
使用注解来描述HTTP请求:

支持URL参数替换和查询。
将对象转化为一个Request Body(例如:JSON、协议缓冲区)。
多部分Request Body和文件上传。
API介绍
为接口的方法添加注解,其参数指明这个请求如何操作。

请求方法
每个方法必须含有HTTP注解(请求方法和相对URL地址)。有5个内置的注解:GET, POST, PUT, DELETE, and HEAD。相对URL地址在注解中指定。

@GET("top250")
同样,可以在URL上指定查询参数。

@GET("users/list?sort=desc")
URL操作
一个请求的URL可以使用替换块和参数来进行URL的动态的替换。替换块的格式:{字符串}。需要替换的部分需要使用相同的字符串和@Path注解。

@GET("{type}250")
Call<MovieEntity> getTopMovie(@Path("type") String type,@Query("start") int start, @Query("count") int count);
同样可以添加查询参数

扫描二维码关注公众号,回复: 10018643 查看本文章

@GET("top250")
Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
对于复杂的查询参数组合,可以使用Map集合。

@GET("{type}250")
Call<MovieEntity> getTopMovie(@Path("type") String type,@QueryMap Map<String,Integer> options);

Map<String,Integer> options = new HashMap<>();
options.put("start",1);
options.put("count",2);
Call<MovieEntity> topMovie = movieService.getTopMovie("top",options);
请求主体
使用@Body可以将一个对象作为HTTP的请求主体。

@POST("users/new")
Call<User> createUser(@Body User user);
指定的对象将使用"Retrofit"指定的转换器进行转换。如果没有添加转换器,就只可以使用RequestBody。

FORM ENCODED 和 MULTIPART
方法同样可以声明表单编码和复合数据。

表单编码数据发送当存在@FormUrlEncoded注解。每个键值对的key为@Filed的部分,Value为Object。

@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
使用@Multipart来实现Multipart的请求。使用@Part注解来声明内容。

@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
Multipart parts使用Retrofit的转换器,或者实现RequestBody。

请求头操作
使用@Headers来设置请求头。

@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();
多个

@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
注意:相同名字的请求头不会覆盖,而是都包含在请求头中。

一个请求头使用@Header注释可以动态更新。@Header必须提供相应的参数。如果该值为null,头就会被忽略掉。另外,valeu会进行toString。

@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
如果请求头需要应用在每个请求上,请使用'OkHttp interceptor'

同步和异步
每个Call实例可以执行同步或者异步请求。每个实例只能使用一次,但是可以使用clone()方法创建一个新的实例来操作。

在Android中,callback会在UI线程中执行,在JVM上,callback会在请求执行的线程上执行。

Retrofit的配置
Retrofit是一个将HTTP的API接口转化为可被调用的对象的类。默认的,Retrofit提供默认的配置,当然,你可以自定义。

转换器
默认情况下,Retrofit只能反序列化HTTP的主体到okhttp的ResponseBody,并且@Body注解只能接收RequestBody的类型数据。

转换器可以被添加来支持其它类型。下面是6个流行的序列化库来方便操作。

* 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

* Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
例子:生成一个使用Gson反序列的API接口实现类,通过GsonConverterFactory转换器。

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
自定义转换器

Create a class that extends the Converter.Factory class and pass in an instance when building your adapter.

简介

Retrofit 是 Square 推出的 HTTP 框架,主要用于 Android 和 Java。Retrofit 将网络请求变成方法的调用,使用起来非常简洁方便。

模型

retrofit模型如下:


 
 

retrofit模型

  1. POJO或模型实体类 : 从服务器获取的JSON数据将被填充到这种类的实例中。
  2. 接口 : 我们需要创建一个接口来管理像GET,POST...等请求的URL,这是一个服务类。
  3. RestAdapter类 : 这是一个REST客户端(RestClient)类,retrofit中默认用的是Gson来解析JSON数据,你也可以设置自己的JSON解析器

使用

  • 创建一个Retrofit 对象(核心用法一)
    Retrofit retrofit = new Retrofit.Builder()
    .addConverterFactory(GsonConverterFactory.create())//解析方法
    //这里建议:- Base URL: 总是以/结尾;- @Url: 不要以/开头
    .baseUrl("http://102.10.10.132/api/")
    .build();

  • 接口申明(核心用法二)

    按照一个http请求对应的写法
    http://102.10.10.132/api/News/1
    http://102.10.10.132/api/News/{资讯id}

      public interface NewsService {
        /**
         * 根据newsid获取对应的资讯数据
         * 如果不需要转换成Json数据,可以用了ResponseBody;
         * @param newsId
         * @return call
         */
        


    http://102.10.10.132/api/News/1/类型1
    http://102.10.10.132/api/News/{资讯id}/{类型}

      @GET("News/{newsId}/{type}")
      Call<NewsBean> getItem(@Path("newsId") String newsId, @Path("type") String type); 

    样式3(参数在URL问号之后)

    http://102.10.10.132/api/News?newsId=1
    http://102.10.10.132/api/News?newsId={资讯id}

      @GET("News")
      Call<NewsBean> getItem(@Query("newsId") String newsId); 


    http://102.10.10.132/api/News?newsId=1&type=类型1
    http://102.10.10.132/api/News?newsId={资讯id}&type={类型}

      @GET("News")
      Call<NewsBean> getItem(@Query("newsId") String newsId, @Query("type") String type); 

    样式4(多个参数在URL问号之后,且个数不确定)

    http://102.10.10.132/api/News?newsId=1&type=类型1...
    http://102.10.10.132/api/News?newsId={资讯id}&type={类型}...

      

    也可以

      

    POST

    样式1(需要补全URL,post的数据只有一条reason)

    http://102.10.10.132/api/Comments/1
    http://102.10.10.132/api/Comments/{newsId}

      @FormUrlEncoded
      @POST("Comments/{newsId}") Call<Comment> reportComment( @Path("newsId") String commentId, @Field("reason") String reason); 

    样式2(需要补全URL,问号后加入access_token,post的数据只有一条reason)

    http://102.10.10.132/api/Comments/1?access_token=1234123
    http://102.10.10.132/api/Comments/{newsId}?access_token={access_token}

      @FormUrlEncoded
      @POST("Comments/{newsId}") Call<Comment> reportComment( @Path("newsId") String commentId, @Query("access_token") String access_token, @Field("reason") String reason); 

    样式3(需要补全URL,问号后加入access_token,post一个body(对象))

    http://102.10.10.132/api/Comments/1?access_token=1234123
    http://102.10.10.132/api/Comments/{newsId}?access_token={access_token}

      @POST("Comments/{newsId}")
      Call<Comment> reportComment( @Path("newsId") String commentId, @Query("access_token") String access_token, @Body CommentBean bean); 

    上传文件的
    public interface FileUploadService {
    @Multipart
    @POST("upload")
    Call<ResponseBody> upload(@Part("description") RequestBody description,
    @Part MultipartBody.Part file);
    }

    如果你需要上传文件,和我们前面的做法类似,定义一个接口方法,需要注意的是,这个方法不再有 @FormUrlEncoded 这个注解,而换成了 @Multipart,后面只需要在参数中增加 Part 就可以了。

      //构建要上传的文件
      File file = new File(filename); RequestBody requestFile = RequestBody.create(MediaType.parse("application/otcet-stream"), file); MultipartBody.Part body = MultipartBody.Part.createFormData("aFile", file.getName(), requestFile); String descriptionString = "This is a description"; RequestBody description = RequestBody.create( MediaType.parse("multipart/form-data"), descriptionString); 

    DELETE

    样式1(需要补全URL)

    http://102.10.10.132/api/Comments/1
    http://102.10.10.132/api/Comments/{newsId}
    {access_token}

      @DELETE("Comments/{commentId}") Call<ResponseBody> deleteNewsCommentFromAccount( @Path("commentId") String commentId); 

    样式2(需要补全URL,问号后加入access_token)

    http://102.10.10.132/api/Comments/1?access_token=1234123
    http://102.10.10.132/api/Comments/{newsId}?access_token={access_token}

      @DELETE("Comments/{commentId}")
      Call<ResponseBody> deleteNewsCommentFromAccount( @Path("accountId") String accountId, @Query("access_token") String access_token); 

    PUT(这个请求很少用到,例子就写一个)

    http://102.10.10.132/api/Accounts/1
    http://102.10.10.132/api/Accounts/{accountId}

      @PUT("Accounts/{accountId}")
      Call<ExtrasBean> updateExtras( @Path("accountId") String accountId, @Query("access_token") String access_token, @Body ExtrasBean bean); 
  • 创建访问API的请求(核心用法三)
    NewsService api = retrofit.create(NewsService .class);
    Call<News> call = service.getNews("123456");

  • 同步调用(核心用法四)
    News news = call.execute();

  • 异步调用(核心用法五)
    call.enqueue(new Callback<News>(){
    @Override
    public void onResponse(Response<News> response) {
    //成功返回数据后在这里处理,使用response.body();获取得到的结果
    News news = response.body();
    }
    @Override
    public voidonFailure(Throwable t) {
    //请求失败在这里处理
    }
    });

  • 取消请求(核心用法六)
    call.cancel();
    完成以上步骤就可以实现一个简单的网络请求了。

Retrofit注解

方法注解,包含@GET、@POST、@PUT、@DELETE、@PATH、@HEAD、@OPTIONS、@HTTP。
标记注解,包含@FormUrlEncoded、@Multipart、@Streaming。
参数注解,包含@Query,@QueryMap、@Body、@Field,@FieldMap、@Part,@PartMap。
其他注解,@Path、@Header,@Headers、@Url

  • @HTTP:可以替代其他方法的任意一种

     /**
       * method 表示请的方法,不区分大小写
       * path表示路径
       * hasBody表示是否有请求体
       */
      
  • @Url:使用全路径复写baseUrl,适用于非统一baseUrl的场景。

      
  • @Streaming:用于下载大文件

      
  • 动态设置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);
 
 

猜你喜欢

转载自www.cnblogs.com/awkflf11/p/12537138.html