IOException
s being wrapped in UndeclaredThrowableException
in rare cases when using
Response<..>
as a return type for Kotlin 'suspend' functions.IOException
s being wrapped in UndeclaredThrowableException
in rare cases.ResponseBody
for responses created by Response.error
.New: Support suspend
modifier on functions for Kotlin! This allows you to express the asynchrony of HTTP requests
in an idiomatic fashion for the language.
@GET("users/{id}")
suspend fun user(@Path("id") id: Long): User
Behind the scenes this behaves as if defined as fun user(...): Call<User>
and then invoked with Call.enqueue
.
You can also return Response<User>
for access to the response metadata.
Currently this integration only supports non-null response body types. Follow issue 3075 for nullable type support.
New: @Tag
parameter annotation for setting tags on the underlying OkHttp Request
object. These can be read
in CallAdapter
s or OkHttp Interceptor
s for tracing, analytics, varying behavior, and more.
New: @SkipCallbackExecutor
method annotation will result in your Call
invoking its Callback
on the
background thread on which the HTTP call was made.
New: Support OkHttp's Headers
type for @HeaderMap
parameters.
New: Add Retrofit.Builder.baseUrl(URL)
overload.
Fix: Add embedded R8/ProGuard rule which retains Retrofit interfaces (while still allowing obfuscation). This is needed because R8 running in 'full mode' (i.e., not in ProGuard-compatibility mode) will see that there are no subtypes of these interfaces and rewrite any code which references instances to null.
Fix: Mark HttpException.response()
as @Nullable
as serializing the exception does not retain this instance.
Fix: Fatal errors (such as stack overflows, out of memory, etc.) now propagate to the OkHttp Dispatcher
thread
on which they are running.
Fix: Ensure JAX-B converter closes the response body when an exception is thrown during deserialization.
Fix: Ignore static methods when performing eager validation of interface methods.
Fix: Ensure that calling source()
twice on the ResponseBody
passed to a Converter
always returns the same
instance. Prior to the fix, intermediate buffering would cause response data to be lost.
Unit
type. This behaves the same as Java's Void
where the body
content is ignored and immediately discarded.Optional
and CompletableFuture
types. Previously the 'converter-java8'
and 'adapter-java8' dependencies were needed and explicitly adding Java8OptionalConverterFactory
and/or
Java8CallAdapterFactory
to your Retrofit.Builder
in order to use these types. Support is now built-in and
those types and their artifacts are marked as deprecated.Invocation
class provides a reference to the invoked method and argument list as a tag on the
underlying OkHttp Call
. This can be accessed from an OkHttp interceptor for things like logging, analytics,
or metrics aggregation.Retrofit
which allows you call create
passing the interface type only as
a generic parameter (e.g., retrofit.create<MyService>()
).Response.success
overload which allows specifying a custom 2xx status code.Calls.failure
overload which allows passing any Throwable
subtype.onSubscribe
.RxJavaPlugins
assembly hook when creating an RxJava 2 type.Optional
converters delegate properly. This ensures that converters
registered prior to the optional converter can be used for deserializing the body type.@Path
values from participating in path-traversal. This ensures untrusted input passed as
a path value cannot cause you to make a request to an un-intended relative URL.RuntimeException
or IOException
when it fails.@QueryName
or @QueryMap
precedes a @Url
parameter.Retrofit.Builder
exposes mutable lists of the added converter and call adapter factories.Future
.Error
s from callbacks (usually OutOfMemoryError
).Call
cancelation with RxJava unsubscription/disposal. Prior to
this change, canceling of a Call
would prevent a cancelation exception from propagating down
the Rx stream.Retrofit now uses @Nullable
to annotate all possibly-null values. We've
added a compile-time dependency on the JSR 305 annotations. This is a
provided dependency and does not need to be included in
your build configuration, .jar
file, or .apk
. We use
@ParametersAreNonnullByDefault
and all parameters and return types are
never null unless explicitly annotated @Nullable
.
Warning: this release is source-incompatible for Kotlin users. Nullability was previously ambiguous and lenient but now the compiler will enforce strict null checks.
New: Converters added for Java 8's and Guava's Optional
which wrap a potentially-nullable
response body. These converters still rely on normal serialization library converters for parsing
the response bytes into an object.
New: String converters that return null
for an @Query
or @Field
parameter are now skipped.
New: The mock module's NetworkBehavior
now throws a custom subclass of IOException
to more
clearly indicate the exception's source.
RxJava 1.x converter updated to 1.3.0 which stabilizes the use of Completable
.
Fix: Add explicit handling for OnCompleteFailedException
, OnErrorFailedException
, and
OnErrorNotImplementedException
for RxJava 1.x to ensure they're correct delivered to the
plugins/hooks for handling.
Fix: NoSuchElementException
thrown when unsubscribing from an RxJava 1.x Single
.
@QueryName
annotation allows creating a query parameter with no '=' separator or value.toString()
implementations for Response
and Result
.createAsync()
to RxJava 1.x call adapter factory which executes requests using
Call.enqueue()
using the underlying HTTP client's asynchronous support.NetworkBehavior
now allows setting an error percentage and returns HTTP errors when triggered.HttpException
has been moved into the main artifact and should be used instead of the versions
embedded in each adapter (which have been deprecated).CallAdapter
from the adapt
method to the enclosing
class. This is a source-incompatible but binary-compatible change which is only relevant if you are
implementing your own CallAdapter
s.Call
in Retrofit's Call
.String
type on non-body parameters. This allows user
converters to handle cases such as when annotating string parameters instead of them always using
the raw string.@HeaderMap
annotation and support for supplying an arbitrary number of headers to an endpoint.@JsonAdapter
annotations on the @Body
parameter and on the method will be propagated to Moshi
for creating the request and response adapters, respectively.Content-Type
encoding of XML responses when deserializing response bodies.NetworkBehavior
.
They had the potential to be misleading and look like a library issue.Content-Type
headers supplied via @Header
or @Headers
.ProtoConverterFactory.createWithRegistry()
method accepts an extension registry to be used
when deserializing protos.Call
instance to Callback
's onResponse
and onFailure
methods such
that calling clone()
retains the correct threading behavior.HttpUrl
as a @Url
parameter type.@Part
parameters using OkHttp's MultipartBody.Part
.Observable
s created from the RxJavaCallAdapterFactory.Retrofit 2 is a major release focused on extensibility. The API changes are numerous but solve shortcomings of the previous version and provide a path for future enhancement.
Because the release includes breaking API changes, we're changing the project's package name from
retrofit
to retrofit2
. This should make it possible for large applications and libraries to
migrate incrementally. The Maven group ID is now com.squareup.retrofit2
. For an explanation of
this strategy, see Jake Wharton's post, Java Interoperability Policy for Major Version
Updates.
Service methods return Call<T>
. This allows them to be executed synchronously or
asynchronously using the same method definition. A Call
instance represents a single
request/response pair so it can only be used once, but you can clone()
it for re-use.
Invoking cancel()
will cancel in-flight requests or prevent the request from even being
performed if it has not already.
Multiple converters for multiple serialization formats. API calls returning different
formats (like JSON, protocol buffers, and plain text) no longer need to be separated into
separate service interfaces. Combine them together and add multiple converters. Converters are
chosen based on the response type you declare. Gson is no longer included by default, so you will
always need to add a converter for any serialization support. OkHttp's RequestBody
and
ResponseBody
types can always be used without adding one, however.
Call adapters allow different execution mechanisms. While Call
is the built-in mechanism,
support for additional ones can be added similar to how different converters can be added.
RxJava's Observable
support has moved into a separate artifact as a result, and support for
Java 8's CompletableFuture
and Guava's ListenableFuture
are also provided as additional
artifacts.
Generic response type includes HTTP information and deserialized body. You no longer have to
choose between the deserialized body and reading HTTP information. Every Call
automatically
receives both via the Response<T>
type and the RxJava, Guava, and Java 8 call adapters also
support it.
@Url for hypermedia-like APIs. When your API returns links for pagination, additional
resources, or updated content they can now be used with a service method whose first parameter
is annotated with @Url
.
Changes from beta 4:
RxJavaCallAdapterFactory
now supports service methods which return Completable
which
ignores and discards response bodies, if any.RxJavaCallAdapterFactory
supports supplying a default Scheduler
which will be used
for subscribeOn
on returned Observable
, Single
, and Completable
instances.MoshiConverterFactory
supports creating an instance which uses lenient parsing.@Part
can omit the part name and use OkHttp's MultipartBody.Part
type for supplying
parts. This lets you customize the headers, name, and filename and provide the part body in a
single argument.BaseUrl
interface and support for changeable base URLs was removed. This functionality
can be done using an OkHttp interceptor and a sample showcasing it was added.Response.isSuccess()
was renamed to Response.isSuccessful()
for parity with the name of
OkHttp's version of that method.GsonConverterFactory
now honors settings on the Gson
instance (like leniency).ScalarsConverterFactory
now supports primitive scalar types in addition to boxed for
response body parsing.Retrofit.callbackExecutor()
may now return an executor even when one was not explicitly
provided. This allows custom CallAdapter.Factory
implementations to use it when triggering
callbacks to ensure they happen on the appropriate thread for the platform (e.g., Android).Call
instance is now passed to both onResponse
and onFailure
methods of Callback
. This aids
in detecting when onFailure
is called as a result of Call.cancel()
by checking Call.isCanceled()
.Call.request()
returns (optionally creating) the Request
object for the call. Note: If this is
called before Call.execute()
or Call.enqueue()
this will do relatively expensive work synchronously.
Doing so in performance-critical sections (like on the Android main thread) should be avoided.adapter-guava
module provides a CallAdapter.Factory
for Guava's ListenableFuture
.adapter-java8
module provides a CallAdapter.Factory
for Java 8's CompleteableFuture
.ScalarsConverterFactory
(from converter-scalars
module) now supports parsing response bodies
into either String
, the 8 primitive types, or the 8 boxed primitive types.retrofit2.converter.<name>
. This prevents type
collisions when many converters are simultaneously in use.CallAdapter.Factory
for a method return type now
correctly list the CallAdapter.Factory
instances checked./
characters in @Path
replacements when encoded = true
.retrofit2.*
package name. The Maven groupId is now
com.squareup.retrofit2
. This is in accordance with the
Java Interoperability Policy for Major Version Updates.
With this change Retrofit 2.x can coexiest with Retrofit 1.x in the same project.okhttp3.*
) and Maven groupId (com.squareup.okhttp3
) which allow
it to coexist with OkHttp 2.x in the same project.@Path
,
@Query
, @Header
, etc.). Converter.Factory
has a new stringConverter
method which receives the
parameter type and annotations and can return a converter for that type. This allows providing custom
rendering of types like Date
, User
, etc. to a string before being used for its purpose. A default
converter will call toString()
for any type which retains the mimics the previous behavior.Call.Factory
type is now used as the HTTP client rather than using the OkHttpClient
type
directly (OkHttpClient
does implement Call.Factory
). A callFactory
method has been added to both
Retrofit.Builder
and Retrofit
to allow supplying alternate implementations of an HTTP client. The
client(OkHttpClient)
method on Retrofit.Builder
still exists as a convenience.isExecuted()
method returns whether a Call
has been synchronously or asynchronously executed.isCanceled()
method returns whether a Call
has been canceled. Use this in onFailure
to determine
whether the callback was invoked from cancellation or actual transport failure.converter-scalars
module provides a Converter.Factory
for converting String
, the 8 primitive
types, and the 8 boxed primitive types as text/plain
bodies. Install this before your normal converter
to avoid passing these simple scalars through, for example, a JSON converter.Converter.Factory
methods now receive a Retrofit
instance which also now has methods for querying
the next converter for a given type. This allows implementations to delegate to others and provide
additional behavior without complete reimplementation.@OPTIONS
annotation more easily allows for making OPTIONS requests.@Part
annotation now supports List
and array types.@Url
annotation now allows using java.net.URI
or android.net.Uri
(in addition to String
)
as parameter types for providing relative or absolute endpoint URLs dynamically.retrofit-mock
module has been rewritten with a new BehaviorDelegate
class for implementing
fake network behavior in a local mock implementation of your service endpoints. Documentation and more
tests are forthcoming, but the SimpleMockService
demonstrates its use for now.Response
type and OkHttp's Response
type as the response body type given to
a Call
(i.e., Call<Response>
). OkHttp's ResponseBody
type is the correct one to use when the raw
body contents are desired.Gson
instance (such as serializeNulls
).
This requires Gson 2.4 or newer.Retrofit
instance to the onResponse
callback of Callback
has been reverted. There are too many edge cases around providing the Retrofit
object in order to allow
deserialization of the error body. To accommodate this use case, pass around the Retrofit
response
manually or implement a custom CallAdapter.Factory
does so automatically.Void
(e.g., Call<Void>
) will ignore and discard the response body. This
can be used when there will be no response body (such as in a 201 response) or whenever the body is not
needed. @Head
requests are now forced to use this as their response type.validateEagerly()
method on Retrofit.Builder
will verify the correctness of all service methods
on calls to create()
instead of lazily validating on first use.Converter
is now parameterized over both 'from' and 'to' types with a single convert
method.
Converter.Factory
is now an abstract class and has factory methods for both request body and response
body.Converter.Factory
and CallAdapter.Factory
now receive the method annotations when being created
for a return/response type and the parameter annotations when being created for a parameter type.callAdapter()
method on Retrofit
allows querying a CallAdapter
for a given type. The
nextCallAdapter()
method allows delegating to another CallAdapter
from within a CallAdapter.Factory
.
This is useful for composing call adapters to incrementally build up behavior.requestConverter()
and responseConverter()
methods on Retrofit
allow querying a Converter
for
a given type.onResponse
method in Callback
now receives the Retrofit
instance. Combined with the
responseConverter()
method on Retrofit
, this provides a way of deserializing an error body on Response
.
See the DeserializeErrorBody
sample for an example.MoshiConverterFactory
has been updated for its v1.0.0.ResponseBody
for the response type or RequestBody
for a parameter type is now correctly
identified. Previously these types would erroneously be passed to the supplied converter.@Path
values has been corrected to conform to OkHttp's HttpUrl
.@Multipart
.Observable
and Single
-based execution of requests now behave synchronously (and thus requires
subscribeOn()
for running in the background).GsonConverterFactory
to honor the configuration of the Gson
instances (such as not
serializing null values, the default).Call
encapsulates a single request/response HTTP call. A call can by run synchronously
via execute()
or asynchronously via enqueue()
and can be canceled with cancel()
.Response
is now parameterized and includes the deserialized body object.@Url
parameter annotation allows passing a complete URL for an endpoint.TypedInput
and TypedOutput
(and its
implementations), Request
, and Header
have been replaced with OkHttp types like RequestBody
,
ResponseBody
, and Headers
.CallAdapter
(and Factory
) provides extension point for supporting multiple execution
mechanisms. An RxJava implementation is provided by a sibling module.Converter
(and Factory
) provides extension point for supporting multiple serialization
mechanisms. Gson, Jackson, Moshi, Protobuf, Wire, and SimpleXml implementations are provided by sibling
modules.okhttp-urlconnection
shim.@Header
now accepts a List
or array for a type.@Field
and @FieldMap
now have options for enabling or disabling URL encoding of names and values.com.netflix.rxjava
to
io.reactivex
which is why the minor version was bumped.null
request arguments for HEADERS_AND_ARGS
log level.RetrofitError
's getKind()
now disambiguates the type of error represented.HEADERS_AND_ARGS
log level displays parameters passed to method invocation along with normal
header list.@Part
and @PartMap
now support specifying the Content-Transfer-Encoding
of their respective
values.@Path
, @Query
, and @QueryMap
now have options for enabling or disabling URL encoding on
names (where appropriate) and values.@Header
now accepts all object types, invoking String.valueOf
when neccesary.@Path
replacement block ({name}
) in a query parameter now suggested @Query
in
the exception message.Content-Type
override is specified on requests without a body.WireConverter
now correctly throws ConversionException
on incorrect MIME types for parity with
ProtoConverter
.Content-Type
on AppEngine requests.MockRestAdapter
's RxJava support now correctly schedules work on the HTTP executor, specifically
when chaining multiple requests together.null
mock exception bodies and use the success type from the declared service interface.@Streaming
on a Response
type will skip buffering the body to a byte[]
before delivering.RequestInterceptor
is now applied at the time of Observable
subscription rather
than at the time of its creation.Callback
subtypes are now supported when using MockRestAdapter
.RetrofitError
now contains a useful message indicating the reason for the failure.Response#getBody
when null
body now correctly returns instead of throwing an NPE.Content-Type
and Content-Length
headers are no longer automatically added to the header list
on the Request
object. This reverts erroneous behavior added in v1.5.0. Custom Client
implementations
should revert to adding these headers based on the TypedInput
body of the Request
.@PartMap
annotation accepts a Map
of key/value pairs for multi-part.MockRestAdpater
uses the ErrorHandler
from its parent RestAdapter
.Content-Type
can be overridden with a method-level or paramter header annotation.ErrorHandler
is supplied it will be invoked for Callback
and Observable
methods.PATCH
method using HttpUrlConnection
is no longer supported. Add the
OkHttp jar to your project if you need this behavior.Client
implementations should no longer set Content-Type
or Content-Length
headers
based on the TypedInput
body of the Request
. These headers will now be added automatically
as part of the standard Request
header list.@QueryMap
, @EncodedFieldMap
, and @FieldMap
now correctly detect Map
-based parameter
types.@Query
and @EncodedQuery
now accept List
or arrays for multiple values.@QueryMap
and @EncodedQueryMap
accept a Map
of key/value pairs for query parameters.@Field
now accepts List
or arrays for multiple values.@FieldMap
accepts a Map
of name/value pairs for form URL-encoded request bodies.Endpoint
replaces Server
as the representation of the remote API root. The Endpoints
utility class contains factories methods for creating instances. Server
and ChangeableServer
are now deprecated.SimpleXmlConverter
and JacksonConverter
now have a default constructor.Response
now includes the URL.Observable
support! Declare a return type of Observable<Foo>
on your service
interfaces to automatically get an observable for that request. (Experimental API)ObjectMapper
's type factory when deserializing (Jackson converter).OkHttpClient
instances.RestAdapter.Builder
's setConverter
.@EncodedPath
and @EncodedQuery
annotations allow provided path and query params that
are already URL-encoded.@PATCH
HTTP method annotation.UrlConnectionClient
.RequestInterceptor
during method invocation rather than at request execution time.setDebug
to setLogLevel
on RestAdapter
and RestAdapter.Builder
and provide
two levels of logging via LogLevel
.@Headers
-defined headers are correctly added to requests.null
for a @Part
-annotated argument to remove it from the multipart
request body.RequestInterceptor
to replace RequestHeaders
. An interceptor provided to the
RestAdapter.Builder
will be called for every request and allow setting both headers and
additional path parameter replacements.ErrorHandler
for customizing the exceptions which are thrown when synchronous methods
return non-200 error codes.null
as a value for method parameters.
@Path
- Forbidden@Query
- Allowed@Field
- Allowed@Part
- Forbidden@Body
- Forbidden@Header
- AllowedInitial release.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。