博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
retrofit使用教程
阅读量:7082 次
发布时间:2019-06-28

本文共 5897 字,大约阅读时间需要 19 分钟。

hot3.png

Introduction

Retrofit turns your HTTP API into a Java interface.

public interface GitHubService {  @GET("users/{user}/repos")  Call
> listRepos(@Path("user") String user);}

The Retrofit class generates an implementation of the GitHubService interface.

Retrofit retrofit = new Retrofit.Builder()    .baseUrl("https://api.github.com/")    .build();GitHubService service = retrofit.create(GitHubService.class);

Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.

Call
> repos = service.listRepos("octocat");

Use annotations to describe the HTTP request:

  • URL parameter replacement and query parameter support
  • Object conversion to request body (e.g., JSON, protocol buffers)
  • Multipart request body and file upload

API Declaration

Annotations on the interface methods and its parameters indicate how a request will be handled.

REQUEST METHOD

Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations:GETPOSTPUTDELETE, and HEAD. The relative URL of the resource is specified in the annotation.

@GET("users/list")

You can also specify query parameters in the URL.

@GET("users/list?sort=desc")

URL MANIPULATION

A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by {

 and }. A corresponding parameter must be annotated with  using the same string.

@GET("group/{id}/users")Call
> groupList(@Path("id") int groupId);

Query parameters can also be added.

@GET("group/{id}/users")Call
> groupList(@Path("id") int groupId, @Query("sort") String sort);

For complex query parameter combinations a Map can be used.

@GET("group/{id}/users")Call
> groupList(@Path("id") int groupId, @QueryMap Map
options);

REQUEST BODY

An object can be specified for use as an HTTP request body with the  annotation.

@POST("users/new")Call
createUser(@Body User user);

The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBodycan be used.

FORM ENCODED AND MULTIPART

Methods can also be declared to send form-encoded and multipart data.

Form-encoded data is sent when @FormUrlEncoded is present on the method. Each key-value pair is annotated with containing the name and the object providing the value.

@FormUrlEncoded@POST("user/edit")Call
updateUser(@Field("first_name") String first, @Field("last_name") String last);

Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part annotation.

@Multipart@PUT("user/photo")Call
updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

Multipart parts use one of Retrofit's converters or they can implement RequestBody to handle their own serialization.

HEADER MANIPULATION

You can set static headers for a method using the @Headers annotation.

@Headers("Cache-Control: max-age=640000")@GET("widget/list")Call
> widgetList();
@Headers({    "Accept: application/vnd.github.v3.full+json",    "User-Agent: Retrofit-Sample-App"})@GET("users/{username}")Call
getUser(@Path("username") String username);

Note that headers do not overwrite each other. All headers with the same name will be included in the request.

A request Header can be updated dynamically using the @Header annotation. A corresponding parameter must be provided to the@Header. If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.

@GET("user")Call
getUser(@Header("Authorization") String authorization)

Headers that need to be added to every request can be specified using an .

SYNCHRONOUS VS. ASYNCHRONOUS

Call instances can be executed either synchronously or asynchronously. Each instance can only be used once, but calling clone()will create a new instance that can be used.

On Android, callbacks will be executed on the main thread. On the JVM, callbacks will happen on the same thread that executed the HTTP request.

Retrofit Configuration

Retrofit is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization.

CONVERTERS

By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type and it can only accept its RequestBody type for@Body.

Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.

  • com.squareup.retrofit2:converter-gson
  • com.squareup.retrofit2:converter-jackson
  • com.squareup.retrofit2:converter-moshi
  • com.squareup.retrofit2:converter-protobuf
  • com.squareup.retrofit2:converter-wire
  • com.squareup.retrofit2:converter-simplexml
  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

Here's an example of using the GsonConverterFactory class to generate an implementation of the GitHubService interface which uses Gson for its deserialization.

Retrofit retrofit = new Retrofit.Builder()    .baseUrl("https://api.github.com")    .addConverterFactory(GsonConverterFactory.create())    .build();GitHubService service = retrofit.create(GitHubService.class);

CUSTOM CONVERTERS

If you need to communicate with an API that uses a content-format that Retrofit does not support out of the box (e.g. YAML, txt, custom format) or you wish to use a different library to implement an existing format, you can easily create your own converter. Create a class that extends the  and pass in an instance when building your adapter.

转载于:https://my.oschina.net/u/581142/blog/717950

你可能感兴趣的文章
通过git远程管理自己本地的工程
查看>>
scala中的下划线_
查看>>
QTreeWidget 获取被双击的子项的层次路径
查看>>
如何调整工作激情
查看>>
数据仓库专题(10)-文本事实和杂项维度
查看>>
VC6下实现remove_reference的方法。
查看>>
数据备份和还原
查看>>
Angular企业级开发(3)-Angular MVC实现
查看>>
SMS系列之一:部署SMS2003 + SP3
查看>>
查看mysql进程--show processlist
查看>>
ProtecTIER网关演绎重复数据删除的硬道理
查看>>
Android 播放Gif 动画
查看>>
(原创)创建windows域---深入理解域概念
查看>>
虚幻4,BP写了一个简单的三线跑酷工程
查看>>
“10亿元身价”CEO的6个密码
查看>>
C++/CLI思辨录之内部指针的两面性
查看>>
谨慎注意WebBrowser控件的DocumentCompleted事件
查看>>
回头再说 005 --温暖的文字和音乐
查看>>
JavaWeb之tomcat安装、配置与使用(一)
查看>>
解: Eclipse+pydev中文显示
查看>>