retrofit入门教程

来源:互联网 发布:淘宝开店 企业店铺 编辑:程序博客网 时间:2024/06/06 07:33

Retrofit

A type-safe HTTP client for Android and Java

简介

Retrofit把Http API 当成一个interfacepublic interface GitHubService {    @Get("users/{user]/repos")    Call<List<Repo>> listRepos(@Path("user") String user);}然后Retrofit通过create获得一个GitHubService接口的一个示例。Retrofit retrofit = new Retrofit.Builder()    .baseUrl("https://api.github.com")    .build();GitHubService service = retrofit.create(GitHubService.class);来自创建的GitHubService的每个调用都可以向远程Web服务器发出同步或异步HTTP请求。Call<List<Repo>> repos = service.listRepos("octocat");使用java的注解去描述HTTP请求:- Url参数可替换,查询参数支持- 对象也已转化成请求体(例如JSON,协议缓冲)- 多块请求体,文件上传

API声明

接口方法和它的参数的注解表明了将如何处理http请求

请求方法

每个方法都必须有个提供请求方法的HTTP注解和相关的URL,总共有五个内置的注解(GET,POST,PUT,DELETE,HEAD)@GET("users/list")你也可以制定查询参数在URL中@GET("users/list?sort=desc")-URL的使用可以使用替代块和参数动态更新请求的url,替换块是{}包围的字符数字字符串。相应的参数必须使用相同的字符串用@Path注释。@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId);也可以添加查询参数。@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);如果是复杂的查询参数可以使用Map代替。@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

请求体

可以指定一个对象作为HTTP的请求体,只是不要忘了添加@Body注解。@POST("users/new")Call<User> createUser(@Body User user);该对象也将使用Retrofit实例上指定的转换器进行转换。如果没有添加转换器,则只能使用RequestBody。当方法上存在@FormUrlEncoded时,将发送表单编码的数据。每个键值对都使用包含名称的@Field和提供值的对象进行注释。@FormUrlEncoded@POST("user/edit")Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);当@Multipart出现在方法上时,将使用多部分请求。每一部分都要使用@Part注释声明。@Multipart@PUT("user/photo")Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);多部分请求时使用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,头就会被忽略掉。否则,toString将被调用在头上,并使用该值。@GET("user")Call<User> getUser(@Header("Authorization") String authorization)需要添加到每个请求的头部可以使用OkHttp拦截器指定。

同步和异步

调用实例可以同步或异步执行。每个实例只能使用一次,但调用clone()将创建一个可以使用的新实例。在Android上,回调将在主线程上执行。在JVM上,回调将发生在执行HTTP请求的同一线程上。

Retrfit配置

Retrofit是将API接口转换为可调用对象的类。默认情况下,Retrofit将为您的平台提供正常默认值,但允许自定义。

转换器

默认情况下,Retrofit只能将HTTP主体反序列化为OkHttp的ResponseBody类型,并且它只能接受@Body的RequestBody类型。可以添加转换器以支持其他类型。六个同级模块适应流行的序列化库,为您提供方便。* 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下面是一个使用GsonConverterFactory类来生成GitHubService接口的实现的示例,该接口使用Gson进行反序列化Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com").addConverterFactory(GsonConverterFactory.create()).build();GitHubService service = retrofit.create(GitHubService.class);

自定义转换器

如果您需要与使用Retrofit不支持开箱即用的内容格式(例如YAML,txt,自定义格式)的API进行通信,或者希望使用其他库来实现现有格式,则可以轻松创建你自己的转换器。创建一个扩展Converter.Factory类的类,并在构建适配器时传递实例。

下载

Retrofit的源码和样例可以在GitHub上下载,[点击下载源码](http://github.com/square/retrofit)

MAVEN

<dependency>    <groupId>com.squareup.retrofit2</groupId>    <artifactId>retrofit</artifactId>    <version>(insert latest version)</version></dependency>

GRADLE

compile 'com.squareup.retrofit2:retrofit:(insert latest version)'Retrofit需要至少Java 7或Android 2.3。

代码混淆

如果在项目中使用Proguard,请在配置中添加以下行:# Platform calls Class.forName on types which do not exist on Android to determine platform.-dontnote retrofit2.Platform# Platform used when running on RoboVM on iOS. Will not be used at runtime.-dontnote retrofit2.Platform$IOS$MainThreadExecutor# Platform used when running on Java 8 VMs. Will not be used at runtime.-dontwarn retrofit2.Platform$Java8# Retain generic type information for use by reflection by converters and adapters.-keepattributes Signature# Retain declared checked exceptions for use by a Proxy instance.-keepattributes Exceptions
1 0
原创粉丝点击