当前位置: 代码迷 >> 综合 >> 6.3 强大的网络请求第三方框架 Retrofit 的介绍和使用未完待翻译
  详细解决方案

6.3 强大的网络请求第三方框架 Retrofit 的介绍和使用未完待翻译

热度:48   发布时间:2023-12-16 16:04:01.0

http://square.github.io/retrofit/ 

Introduction

Retrofit turns your HTTP API into a Java interface. 可以将HTTP 的应用程序接口转化为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. Retrofit 类产生了一个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 请求到远程的webserver

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

Use annotations to describe the HTTP request:

使用注解去描述HTTP请求

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

  • URL 参数替换和query 参数的支持
  • 将对象转化为请求的实体body(例如JSON,protocol Butters -概述Protocol Buffers是Google公司开发的一种数据描述语言,)
  • 多个部分请求body 和文件上传

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

API Declaration ,API 声明

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的注解,这个HTTP的注解提供了请求的方法和相关的URL。一共有五种内置的注解:GET,POST,PUT,DELETE,和HEAD. 相关的资源的URL在注解里面指明。

@GET("users/list")

You can also specify query parameters in the URL. 你也可以在URL里面指定一个query 的参数

@GET("users/list?sort=desc")
URL MANIPULATION ,URL 的操作;

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 可以通过使用替换block块和方法参数来实现自动更新.一个替换块是一个用{ }括号括起来的字符串,一个回应的参数必须是在@Path的 注解里面.用相同的字符串 

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

Query parameters can also be added. 参数Query可以被添加 

@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. 对于复杂的请求参数使用Map 来进行绑定

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

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

作为HTTP返回的body 一个对象可以通过@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, onlyRequestBody can be used.

对象如果使用Retrofit 实例 里面的 转换也 会 被转换的 。如果没有任何的转换,只有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 @Fieldcontaining the name and the object providing the value.如果@FormUrlEncoded 在方法中那么Form-encoded 数据将会发送。每一个 键值对将会使用@Filed的注解,@Filed 包含了额名字和对象,这个对象提供了值。

@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 注解在方法中使用的时候是使用,部分使用@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("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.

@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.

SYNCHRONOUS VS. ASYNCHRONOUS

Call instances can be executed either synchronously or asynchronously. Each instance can only be used once, but callingclone() 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

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 RequestBodytype for @Body.

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

  • 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

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

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 running mvn clean verify.

Before your code can be accepted into the project you must also sign the Individual Contributor License Agreement (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 athttp://www.apache.org/licenses/LICENSE-2.0Unless 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.
  相关解决方案