Retrofit官方简介

GitHub项目主页:https://github.com/square/retrofit

GitHub官方主页:http://square.github.io/retrofit/

官方介绍:

Retrofit

类型安全的HTTP客户端安卓和Java的广场,Inc .)

有关更多信息,请参见网站。

Download

Download the latest JAR or grab via Maven:

<dependency>
  <groupId>com.squareup.retrofit2</groupId>
  <artifactId>retrofit</artifactId>
  <version>2.0.2</version>
</dependency>

or Gradle:

compile 'com.squareup.retrofit2:retrofit:2.0.2'

开发版中可用Sonatype快照的快照存储库。

改造需要至少Java 7或Android 2.3。

Introduction

Retrofit turns your HTTP API into a Java interface.

改造你的HTTP API变成一个Java接口。

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}
The Retrofit class generates an implementation of the GitHubService interface.

改造类生成GitHubService接口的一个实现。

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.

从创建的每个调用GitHubService可以同步或异步HTTP请求到远程网络服务器。

Call<List<Repo>> 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

Note: This site is still in the process of being expanded for the new 2.0 APIs.

使用注释来描述HTTP请求:

URL参数替换和查询参数的支持

请求主体(如对象转换。 、JSON、协议缓冲区)

多部分请求主体和文件上传

注意:这个网站的过程仍在扩展新2.0 api。

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.

每个方法必须有一个HTTP请求注释提供方法和相对URL。 有五个内置注释:GET、POST、PUT、DELETE和头部。 资源的相对URL中指定注释。

@GET("users/list")

You can also specify query parameters in the URL.

您还可以指定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 @Path  using the same string.

请求URL使用替换块和参数可以动态更新方法。 是一个字母数字字符串替换块{和}包围。 相应的参数必须与@ path注释使用相同的字符串。

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

Query parameters can also be added.

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

For complex query parameter combinations a Map can be used.

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
REQUEST BODY

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

可以指定一个对象作为HTTP请求体@Body注释。

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

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

指定的对象也将使用一个转换器转换的改造实例。 如果没有添加转换器,只能使用RequestBody。

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 @Field  containing the name and the object providing the value.

方法也可以声明发送表单编码和多部分数据。

表单编码的数据发送当@FormUrlEncoded存在的方法。 每个键-值对注释@Field包含名称和对象提供的价值。

@FormUrlEncoded
@POST("user/edit")
Call<User> 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存在的方法。 部分使用the@Part注释声明。

@Multipart
@PUT("user/photo")
Call<User> 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注释静态头的方法。

@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);

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.

一个请求头使用@Header注释可以动态更新。 @Header必须提供相应的参数。 如果该值为null,头就会被忽略掉。 否则,toString将呼吁值,以及使用的结果。

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

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

头需要添加到每个请求可以使用一个指定OkHttp拦截器。

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.

调用实例可以同步或异步执行。 每个实例只能使用一次,但是调用clone()将创建一个新的实例,可以使用。

在Android上,回调函数将在主线程上执行。 在JVM上,回调函数会发生在同一线程执行HTTP请求。

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.

改造是通过API接口的类转化为可调用对象。 默认情况下,改造会给你理智的默认为您的平台,但它允许定制。

CONVERTERS

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

默认情况下,改造只能反序列化HTTP的身体进入OkHttp ResponseBody类型和它只能接受其为@Body RequestBody类型。

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

转换器可以添加到其他类型的支持。 六个兄弟模块适应流行序列化库为您的方便。

  • Gsoncom.squareup.retrofit2:converter-gson
  • Jacksoncom.squareup.retrofit2:converter-jackson
  • Moshicom.squareup.retrofit2:converter-moshi
  • Protobufcom.squareup.retrofit2:converter-protobuf
  • Wirecom.squareup.retrofit2:converter-wire
  • Simple XMLcom.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 theGitHubService interface which uses Gson for its deserialization.

这里有一个例子使用GsonConverterFactory类生成theGitHubService接口的一个实现使用Gson反序列化。

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 Converter.Factory classand pass in an instance when building your adapter.

如果你需要与一个API,它使用一个改造内容格式不支持开箱即用的(例如YAML,txt、自定义格式)或你想使用一个不同的库来实现现有的格式,您可以轻松地创建自己的转换器。 创建一个类,扩展了转换器。 工厂classand构建您的适配器时传入一个实例。

Download

↓ Latest JAR

The source code to the Retrofit, its samples, and this website is available on GitHub.

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 requires at minimum Java 7 or Android 2.3.

PROGUARD

If you are using Proguard in your project add the following lines to your configuration:

如果您使用的是混淆器在您的项目中添加以下行您的配置:

-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions

Contributing

If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request.

When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. Please also make sure your code compiles by runningmvn clean verify.

Before your code can be accepted into the project you must also sign the Individual Contributor License Agreement (CLA).

如果你想贡献代码可以通过分叉GitHub库和发送请求。

在提交代码时,请尽一切努力遵循现有的约定和风格以保持尽可能可读的代码。 请确保你的代码编译通过runningmvn清洁验证。

之前您的代码可以接受到项目还必须签署许可协议(CLA)个人因素。

License

Copyright 2013 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

转载于:https://my.oschina.net/whhos/blog/679469

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值