Retrofit官方简介
2016-05-22 00:00
513 查看
摘要:Retrofit官方简介
GitHub项目主页:https://github.com/square/retrofit
GitHub官方主页:http://square.github.io/retrofit/
官方介绍:
有关更多信息,请参见网站。
thelatestJARorgrabviaMaven:
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.0.2</version>
</dependency>
orGradle:
compile'com.squareup.retrofit2:retrofit:2.0.2'
开发版中可用Sonatype快照的快照存储库。
改造需要至少Java7或Android2.3。
改造你的HTTPAPI变成一个Java接口。
publicinterfaceGitHubService{
@GET("users/{user}/repos")
Call<List<Repo>>listRepos(@Path("user")Stringuser);
}
The[code=plain]RetrofitclassgeneratesanimplementationoftheGitHubServiceinterface.[/code]
改造类生成GitHubService接口的一个实现。
EachCallfromthecreatedGitHubServicecanmakeasynchronousorasynchronousHTTPrequesttotheremotewebserver.
从创建的每个调用GitHubService可以同步或异步HTTP请求到远程网络服务器。
UseannotationstodescribetheHTTPrequest:
URLparameterreplacementandqueryparametersupport
Objectconversiontorequestbody(e.g.,JSON,protocolbuffers)
Multipartrequestbodyandfileupload
Note:Thissiteisstillintheprocessofbeingexpandedforthenew2.0APIs.
使用注释来描述HTTP请求:
URL参数替换和查询参数的支持
请求主体(如对象转换。、JSON、协议缓冲区)
多部分请求主体和文件上传
注意:这个网站的过程仍在扩展新2.0api。
注解的接口方法及其参数指示如何处理一个请求。
GET,POST,PUT,DELETE,andHEAD.TherelativeURLoftheresourceisspecifiedintheannotation.
每个方法必须有一个HTTP请求注释提供方法和相对URL。有五个内置注释:GET、POST、PUT、DELETE和头部。资源的相对URL中指定注释。
@GET("users/list")
YoucanalsospecifyqueryparametersintheURL.
您还可以指定URL的查询参数。
@GET("users/list?sort=desc")
{and}.Acorresponding
3ff0
parametermustbeannotatedwith@Pathusingthesamestring.
请求URL使用替换块和参数可以动态更新方法。是一个字母数字字符串替换块{和}包围。相应的参数必须与@path注释使用相同的字符串。
@GET("group/{id}/users")
Call<List<User>>groupList(@Path("id")intgroupId);
Queryparameterscanalsobeadded.
@GET("group/{id}/users")
Call<List<User>>groupList(@Path("id")intgroupId,@Query("sort")Stringsort);
ForcomplexqueryparametercombinationsaMapcanbeused.
@GET("group/{id}/users")
Call<List<User>>groupList(@Path("id")intgroupId,@QueryMapMap<String,String>options);
@Bodyannotation.
可以指定一个对象作为HTTP请求体@Body注释。
@POST("users/new")
Call<User>createUser(@BodyUseruser);
TheobjectwillalsobeconvertedusingaconverterspecifiedontheRetrofitinstance.Ifnoconverterisadded,onlyRequestBodycanbeused.
指定的对象也将使用一个转换器转换的改造实例。如果没有添加转换器,只能使用RequestBody。
Form-encodeddataissentwhen@FormUrlEncodedispresentonthemethod.Eachkey-valuepairisannotatedwith@Fieldcontainingthenameandtheobjectprovidingthevalue.
方法也可以声明发送表单编码和多部分数据。
表单编码的数据发送当@FormUrlEncoded存在的方法。每个键-值对注释@Field包含名称和对象提供的价值。
@FormUrlEncoded
@POST("user/edit")
Call<User>updateUser(@Field("first_name")Stringfirst,@Field("last_name")Stringlast);
Multipartrequestsareusedwhen@Multipartispresentonthemethod.Partsaredeclaredusingthe@Partannotation.
多部分请求时使用@Multipart存在的方法。部分使用the@Part注释声明。
@Multipart
@PUT("user/photo")
Call<User>updateUser(@Part("photo")RequestBodyphoto,@Part("description")RequestBodydescription);
MultipartpartsuseoneofRetrofit'sconvertersortheycanimplementRequestBodytohandletheirownserialization.
@Headersannotation.
你可以设置使用@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")Stringusername);
Notethatheadersdonotoverwriteeachother.Allheaderswiththesamenamewillbeincludedintherequest.
注意,头不会互相覆盖。具有相同名称的所有头文件都包括在请求。
ArequestHeadercanbeupdateddynamicallyusingthe@Headerannotation.Acorrespondingparametermustbeprovidedtothe@Header.Ifthevalueisnull,theheaderwillbeomitted.Otherwise,toStringwillbecalledonthevalue,andtheresultused.
一个请求头使用@Header注释可以动态更新。@Header必须提供相应的参数。如果该值为null,头就会被忽略掉。否则,toString将呼吁值,以及使用的结果。
@GET("user")
Call<User>getUser(@Header("Authorization")Stringauthorization)
HeadersthatneedtobeaddedtoeveryrequestcanbespecifiedusinganOkHttpinterceptor.
头需要添加到每个请求可以使用一个指定OkHttp拦截器。
Callinstancescanbeexecutedeithersynchronouslyorasynchronously.Eachinstancecanonlybeusedonce,butcallingclone()willcreateanewinstancethatcanbeused.
OnAndroid,callbackswillbeexecutedonthemainthread.OntheJVM,callbackswillhappenonthesamethreadthatexecutedtheHTTPrequest.
调用实例可以同步或异步执行。每个实例只能使用一次,但是调用clone()将创建一个新的实例,可以使用。
在Android上,回调函数将在主线程上执行。在JVM上,回调函数会发生在同一线程执行HTTP请求。
RetrofitistheclassthroughwhichyourAPIinterfacesareturnedintocallableobjects.Bydefault,Retrofitwillgiveyousanedefaultsforyourplatformbutitallowsforcustomization.
改造是通过API接口的类转化为可调用对象。默认情况下,改造会给你理智的默认为您的平台,但它允许定制。
ResponseBodytypeanditcanonlyacceptitsRequestBodytypefor@Body.
默认情况下,改造只能反序列化HTTP的身体进入OkHttpResponseBody类型和它只能接受其为@BodyRequestBody类型。
Converterscanbeaddedtosupportothertypes.Sixsiblingmodulesadaptpopularserializationlibrariesforyourconvenience.
转换器可以添加到其他类型的支持。六个兄弟模块适应流行序列化库为您的方便。
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
SimpleXML:com.squareup.retrofit2:converter-simplexml
Scalars(primitives,boxed,andString):com.squareup.retrofit2:converter-scalars
Here'sanexampleofusingtheGsonConverterFactoryclasstogenerateanimplementationoftheGitHubServiceinterfacewhichusesGsonforitsdeserialization.
这里有一个例子使用GsonConverterFactory类生成theGitHubService接口的一个实现使用Gson反序列化。
Retrofitretrofit=newRetrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubServiceservice=retrofit.create(GitHubService.class);
Converter.Factoryclassandpassinaninstancewhenbuildingyouradapter.
如果你需要与一个API,它使用一个改造内容格式不支持开箱即用的(例如YAML,txt、自定义格式)或你想使用一个不同的库来实现现有的格式,您可以轻松地创建自己的转换器。创建一个类,扩展了转换器。工厂classand构建您的适配器时传入一个实例。
↓LatestJAR
ThesourcecodetotheRetrofit,itssamples,andthiswebsiteisavailableonGitHub.
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>(insertlatestversion)</version>
</dependency>
compile'com.squareup.retrofit2:retrofit:(insertlatestversion)'
RetrofitrequiresatminimumJava7orAndroid2.3.
如果您使用的是混淆器在您的项目中添加以下行您的配置:
-dontwarnretrofit2.**
-keepclassretrofit2.**{*;}
-keepattributesSignature
-keepattributesExceptions
Whensubmittingcode,pleasemakeeveryefforttofollowexistingconventionsandstyleinordertokeepthecodeasreadableaspossible.Pleasealsomakesureyourcodecompilesbyrunningmvncleanverify.
BeforeyourcodecanbeacceptedintotheprojectyoumustalsosigntheIndividualContributorLicenseAgreement(CLA).
如果你想贡献代码可以通过分叉GitHub库和发送请求。
在提交代码时,请尽一切努力遵循现有的约定和风格以保持尽可能可读的代码。请确保你的代码编译通过runningmvn清洁验证。
之前您的代码可以接受到项目还必须签署许可协议(CLA)个人因素。
Copyright2013Square,Inc.
LicensedundertheApacheLicense,Version2.0(the"License");
youmaynotusethisfileexceptincompliancewiththeLicense.
YoumayobtainacopyoftheLicenseat
http://www.apache.org/licenses/LICENSE-2.0
Unlessrequiredbyapplicablelaworagreedtoinwriting,software
distributedundertheLicenseisdistributedonan"ASIS"BASIS,
WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
SeetheLicenseforthespecificlanguagegoverningpermissionsand
limitationsundertheLicense.
GitHub项目主页:https://github.com/square/retrofit
GitHub官方主页:http://square.github.io/retrofit/
官方介绍:
Retrofit
类型安全的HTTP客户端安卓和Java的广场,Inc.)有关更多信息,请参见网站。
Download
DownloadorGradle:
开发版中可用Sonatype快照的快照存储库。
改造需要至少Java7或Android2.3。
Introduction
RetrofitturnsyourHTTPAPIintoaJavainterface.改造你的HTTPAPI变成一个Java接口。
改造类生成GitHubService接口的一个实现。
Retrofitretrofit=newRetrofit.Builder() .baseUrl("https://api.github.com/") .build(); GitHubServiceservice=retrofit.create(GitHubService.class);
Each
从创建的每个调用GitHubService可以同步或异步HTTP请求到远程网络服务器。
Call<List<Repo>>repos=service.listRepos("octocat");
UseannotationstodescribetheHTTPrequest:
URLparameterreplacementandqueryparametersupport
Objectconversiontorequestbody(e.g.,JSON,protocolbuffers)
Multipartrequestbodyandfileupload
Note:Thissiteisstillintheprocessofbeingexpandedforthenew2.0APIs.
使用注释来描述HTTP请求:
URL参数替换和查询参数的支持
请求主体(如对象转换。、JSON、协议缓冲区)
多部分请求主体和文件上传
注意:这个网站的过程仍在扩展新2.0api。
APIDeclaration
Annotationsontheinterfacemethodsanditsparametersindicatehowarequestwillbehandled.注解的接口方法及其参数指示如何处理一个请求。
REQUESTMETHOD
EverymethodmusthaveanHTTPannotationthatprovidestherequestmethodandrelativeURL.Therearefivebuilt-inannotations:每个方法必须有一个HTTP请求注释提供方法和相对URL。有五个内置注释:GET、POST、PUT、DELETE和头部。资源的相对URL中指定注释。
YoucanalsospecifyqueryparametersintheURL.
您还可以指定URL的查询参数。
URLMANIPULATION(操作)
ArequestURLcanbeupdateddynamicallyusingreplacementblocksandparametersonthemethod.Areplacementblockisanalphanumericstringsurroundedby3ff0
parametermustbeannotatedwith
请求URL使用替换块和参数可以动态更新方法。是一个字母数字字符串替换块{和}包围。相应的参数必须与@path注释使用相同的字符串。
Call<List<User>>groupList(@Path("id")intgroupId);
Queryparameterscanalsobeadded.
Call<List<User>>groupList(@Path("id")intgroupId,@Query("sort")Stringsort);
Forcomplexqueryparametercombinationsa
Call<List<User>>groupList(@Path("id")intgroupId,@QueryMapMap<String,String>options);
REQUESTBODY
AnobjectcanbespecifiedforuseasanHTTPrequestbodywiththe可以指定一个对象作为HTTP请求体@Body注释。
Call<User>createUser(@BodyUseruser);
Theobjectwillalsobeconvertedusingaconverterspecifiedonthe
指定的对象也将使用一个转换器转换的改造实例。如果没有添加转换器,只能使用RequestBody。
FORMENCODEDANDMULTIPART
Methodscanalsobedeclaredtosendform-encodedandmultipartdata.Form-encodeddataissentwhen
方法也可以声明发送表单编码和多部分数据。
表单编码的数据发送当@FormUrlEncoded存在的方法。每个键-值对注释@Field包含名称和对象提供的价值。
@POST("user/edit")
Call<User>updateUser(@Field("first_name")Stringfirst,@Field("last_name")Stringlast);
Multipartrequestsareusedwhen
多部分请求时使用@Multipart存在的方法。部分使用the@Part注释声明。
@PUT("user/photo")
Call<User>updateUser(@Part("photo")RequestBodyphoto,@Part("description")RequestBodydescription);
Multipartpartsuseoneof
HEADERMANIPULATION(操作)
Youcansetstaticheadersforamethodusingthe你可以设置使用@Headers注释静态头的方法。
@GET("widget/list")
Call<List<Widget>>widgetList();
"Accept:application/vnd.github.v3.full+json",
"User-Agent:Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User>getUser(@Path("username")Stringusername);
Notethatheadersdonotoverwriteeachother.Allheaderswiththesamenamewillbeincludedintherequest.
注意,头不会互相覆盖。具有相同名称的所有头文件都包括在请求。
ArequestHeadercanbeupdateddynamicallyusingthe
一个请求头使用@Header注释可以动态更新。@Header必须提供相应的参数。如果该值为null,头就会被忽略掉。否则,toString将呼吁值,以及使用的结果。
Call<User>getUser(@Header("Authorization")Stringauthorization)
Headersthatneedtobeaddedtoeveryrequestcanbespecifiedusingan
头需要添加到每个请求可以使用一个指定OkHttp拦截器。
SYNCHRONOUSVS.ASYNCHRONOUS
同步与异步OnAndroid,callbackswillbeexecutedonthemainthread.OntheJVM,callbackswillhappenonthesamethreadthatexecutedtheHTTPrequest.
调用实例可以同步或异步执行。每个实例只能使用一次,但是调用clone()将创建一个新的实例,可以使用。
在Android上,回调函数将在主线程上执行。在JVM上,回调函数会发生在同一线程执行HTTP请求。
RetrofitConfiguration
改造是通过API接口的类转化为可调用对象。默认情况下,改造会给你理智的默认为您的平台,但它允许定制。
CONVERTERS
Bydefault,RetrofitcanonlydeserializeHTTPbodiesintoOkHttp's默认情况下,改造只能反序列化HTTP的身体进入OkHttpResponseBody类型和它只能接受其为@BodyRequestBody类型。
Converterscanbeaddedtosupportothertypes.Sixsiblingmodulesadaptpopularserializationlibrariesforyourconvenience.
转换器可以添加到其他类型的支持。六个兄弟模块适应流行序列化库为您的方便。
Scalars(primitives,boxed,andString):
Here'sanexampleofusingthe
这里有一个例子使用GsonConverterFactory类生成theGitHubService接口的一个实现使用Gson反序列化。
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubServiceservice=retrofit.create(GitHubService.class);
CUSTOMCONVERTERS
IfyouneedtocommunicatewithanAPIthatusesacontent-formatthatRetrofitdoesnotsupportoutofthebox(e.g.YAML,txt,customformat)oryouwishtouseadifferentlibrarytoimplementanexistingformat,youcaneasilycreateyourownconverter.Createaclassthatextendsthe如果你需要与一个API,它使用一个改造内容格式不支持开箱即用的(例如YAML,txt、自定义格式)或你想使用一个不同的库来实现现有的格式,您可以轻松地创建自己的转换器。创建一个类,扩展了转换器。工厂classand构建您的适配器时传入一个实例。
Download
ThesourcecodetotheRetrofit,itssamples,andthiswebsiteis
MAVEN
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>(insertlatestversion)</version>
</dependency>
GRADLE
RetrofitrequiresatminimumJava7orAndroid2.3.
PROGUARD
IfyouareusingProguardinyourprojectaddthefollowinglinestoyourconfiguration:如果您使用的是混淆器在您的项目中添加以下行您的配置:
-keepclassretrofit2.**{*;}
-keepattributesSignature
-keepattributesExceptions
Contributing
IfyouwouldliketocontributecodeyoucandosothroughGitHubbyforkingtherepositoryandsendingapullrequest.Whensubmittingcode,pleasemakeeveryefforttofollowexistingconventionsandstyleinordertokeepthecodeasreadableaspossible.Pleasealsomakesureyourcodecompilesbyrunning
Beforeyourcodecanbeacceptedintotheprojectyoumustalsosignthe
如果你想贡献代码可以通过分叉GitHub库和发送请求。
在提交代码时,请尽一切努力遵循现有的约定和风格以保持尽可能可读的代码。请确保你的代码编译通过runningmvn清洁验证。
之前您的代码可以接受到项目还必须签署许可协议(CLA)个人因素。
License
LicensedundertheApacheLicense,Version2.0(the"License");
youmaynotusethisfileexceptincompliancewiththeLicense.
YoumayobtainacopyoftheLicenseat
Unlessrequiredbyapplicablelaworagreedtoinwriting,software
distributedundertheLicenseisdistributedonan"ASIS"BASIS,
WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
SeetheLicenseforthespecificlanguagegoverningpermissionsand
limitationsundertheLicense.
相关文章推荐
- Android Retrofit 2.0框架上传图片解决方案
- 跟我一起看Retrofit 2.0的源码
- http缓存
- android REST APIs 工具 Retrofit的应用
- android开发练习二-Retrofit
- Retrofit之Query注解
- Retrofit之Query注解
- Retrofit 入门--part2
- #Retrofit 入门--Part 1
- Retrofit2源码分析
- 解决找不到okio.buffer.writeUTF8CodePoint 的方法
- Retrofit发送网络请求和解析json实例
- Retrofit+Rxjava
- Android用Retrofit搭建通用网络请求模块
- Retrofit学习一:文档介绍
- Retrofit2(2.x)帮助类(全套)
- Retrofit 的使用详解(下载 多文件上传)
- 关于 Fiddler 出现Response is encoded and may need to be decoded before inspection.
- 深入解析开源项目之Retrofit(二)框架篇
- 深入解析开源项目之Retrofit(一)使用篇