forked from square/retrofit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
355 lines (321 loc) · 20.7 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Retrofit</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A type-safe REST client for Android and Java">
<link href="static/bootstrap-combined.min.css" rel="stylesheet">
<link href="static/app.css" rel="stylesheet">
<link href="static/app-theme.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:400,300italic,100,100italic,300" rel="stylesheet" type="text/css">
<!--[if lt IE 9]><script src="static/html5shiv.min.js"></script><![endif]-->
</head>
<body data-target=".content-nav">
<header>
<div class="container">
<div class="row">
<div class="span5">
<h1>Retrofit</h1>
</div>
<div class="span7">
<menu>
<ul>
<li><a href="#download" class="menu download">Download <span class="version-tag">Latest</span></a></li>
<li><a href="http://github.com/square/retrofit" data-title="View GitHub Project" class="menu github"><img src="static/icon-github.png" alt="GitHub"/></a></li>
<li><a href="http://square.github.io/" data-title="Square Open Source Portal" class="menu square"><img src="static/icon-square.png" alt="Square"/></a></li>
</ul>
</menu>
</div>
</div>
</header>
<section id="subtitle">
<div class="container">
<div class="row">
<div class="span12">
<h2>A type-safe <strong>REST client</strong> for Android and Java</h2>
</div>
</div>
</div>
</section>
<section id="body">
<div class="container">
<div class="row">
<div class="span9">
<h3 id="introduction">Introduction</h3>
<p>Retrofit turns your REST API into a Java interface.</p>
<pre class="prettyprint">public interface GitHubService {
@GET("/users/{user}/repos")
List<Repo> listRepos(@Path("user") String user);
}</pre>
<p>The <code>Retrofit</code> class generates an implementation of the <code>GitHubService</code> interface.</p>
<pre class="prettyprint">Retrofit retrofit = new Retrofit.Builder()
.setEndpoint("https://api.github.com")
.build();
GitHubService service = retrofit.create(GitHubService.class);</pre>
<p>Each call on the generated <code>GitHubService</code> makes an HTTP request to the remote webserver.</p>
<pre class="prettyprint">List<Repo> repos = service.listRepos("octocat");</pre>
<p>Use annotations to describe the HTTP request:</p>
<ul>
<li>URL parameter replacement and query parameter support</li>
<li>Object conversion to request body (e.g., JSON, protocol buffers)</li>
<li>Multipart request body and file upload</li>
</ul>
<h3 id="api-declaration">API Declaration</h3>
<p>Annotations on the interface methods and its parameters indicate how a request will be handled.</p>
<h4>Request Method</h4>
<p>Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations: <code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>, and <code>HEAD</code>. The relative URL of the resource is specified in the annotation.</p>
<pre class="prettyprint">@GET("/users/list")</pre>
<p>You can also specify query parameters in the URL.</p>
<pre class="prettyprint">@GET("/users/list?sort=desc")</pre>
</pre>
<h4>URL Manipulation</h4>
<p>A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by <code>{</code> and <code>}</code>. A corresponding parameter must be annotated with <code>@Path</code> using the same string.</p>
<pre class="prettyprint">@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId);</pre>
<p>Query parameters can also be added.</p>
<pre class="prettyprint">@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @Query("sort") String sort);</pre>
<p>For complex query parameter combinations a <code>Map</code> can be used.</p>
<pre class="prettyprint">@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);</pre>
<h4>Request Body</h4>
<p>An object can be specified for use as an HTTP request body with the <code>@Body</code> annotation.</p>
<pre class="prettyprint">@POST("/users/new")
void createUser(@Body User user, Callback<User> cb);</pre>
<p>The object will also be converted using the <code>Retrofit</code>'s converter.</p>
<h4>Form Encoded and Multipart</h4>
<p>Methods can also be declared to send form-encoded and multipart data.</p>
<p>Form-encoded data is sent when <code>@FormUrlEncoded</code> is present on the method. Each key-value pair is annotated with <code>@Field</code> containing the name and the object providing the value.</p>
<pre class="prettyprint">@FormUrlEncoded
@POST("/user/edit")
User updateUser(@Field("first_name") String first, @Field("last_name") String last);</pre>
<p>Multipart requests are used when <code>@Multipart</code> is present on the method. Parts are declared using the <code>@Part</code> annotation.</p>
<pre class="prettyprint">@Multipart
@PUT("/user/photo")
User updateUser(@Part("photo") TypedFile photo, @Part("description") TypedString description);</pre>
<p>Multipart parts use the <code>Retrofit</code>'s converter or they can implement <code>TypedOutput</code> to handle their own serialization.</p>
<h4>Header Manipulation</h4>
<p>You can set static headers for a method using the <code>@Headers</code> annotation.</p>
<pre class="prettyprint">@Headers("Cache-Control: max-age=640000")
@GET("/widget/list")
List<Widget> widgetList();</pre>
<pre class="prettyprint">@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("/users/{username}")
User getUser(@Path("username") String username);</pre>
<p>Note that headers do not overwrite each other. All headers with the same name will be included in the request.</p>
<p>A request Header can be updated dynamically using the <code>@Header</code> annotation. A corresponding parameter must be provided to the <code>@Header</code>. If the value is null, the header will be omitted. Otherwise, <code>toString</code> will be called on the value, and the result used.</p>
<pre class="prettyprint">@GET("/user")
void getUser(@Header("Authorization") String authorization, Callback<User> callback)</pre>
<p>Headers that need to be added to every request can be specified using a <code>RequestInterceptor</code>. The following code creates a <code>RequestInterceptor</code> that will add a <code>User-Agent</code> header to every request.</p>
<pre class="prettyprint">RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("User-Agent", "Retrofit-Sample-App");
}
};
Retrofit retrofit = new Retrofit.Builder()
.setEndpoint("https://api.github.com")
.setRequestInterceptor(requestInterceptor)
.build();</pre>
<h4>Synchronous vs. Asynchronous vs. Observable</h4>
<p>Methods can be declared for either synchronous or asynchronous execution.</p>
<p>A method with a return type will be executed synchronously.</p>
<pre class="prettyprint">@GET("/user/{id}/photo")
Photo getUserPhoto(@Path("id") int id);</pre>
<p>Asynchronous execution requires the last parameter of the method be a <code>Callback</code>.</p>
<pre class="prettyprint">@GET("/user/{id}/photo")
void getUserPhoto(@Path("id") int id, Callback<Photo> cb);</pre>
<p>On Android, callbacks will be executed on the main thread. For desktop applications callbacks will happen on the same thread that executed the HTTP request.</p>
<p>Retrofit also integrates <a href="https://github.com/ReactiveX/RxJava/wiki">RxJava</a> to support methods with a return type of <code>rx.Observable</code></p>
<pre class="prettyprint">@GET("/user/{id}/photo")
Observable<Photo> getUserPhoto(@Path("id") int id);</pre>
<p>Observable requests are subscribed asynchronously and observed on the same thread that executed the HTTP request. To observe on a different thread (e.g. Android's main thread) call <code>observeOn(Scheduler)</code> on the returned <code>Observable</code>.</p>
<h4>Response Object Type</h4>
<p>HTTP responses are automatically converted to a specified type using the <code>Retrofit</code>'s converter which defaults to JSON. The desired type is declared as the method return type or using the <code>Callback</code> or <code>Observable</code>.
<pre class="prettyprint">@GET("/users/list")
List<User> userList();
@GET("/users/list")
void userList(Callback<List<User>> cb);
@GET("/users/list")
Observable<List<User>> userList();</pre>
<p>For access to the raw HTTP response use the <code>Response</code> type.</p>
<pre class="prettyprint">@GET("/users/list")
Response userList();
@GET("/users/list")
void userList(Callback<Response> cb);
@GET("/users/list")
Observable<Response> userList();</pre>
<h3 id="restadapter-configuration">Retrofit Configuration</h3>
<p><code>Retrofit</code> 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.</p>
<h4>JSON Conversion</h4>
<p>Retrofit uses <a href="https://code.google.com/p/google-gson/">Gson</a> by default to convert HTTP bodies to and from JSON. If you want to specify behavior that is different from Gson's defaults (e.g. naming policies, date formats, custom types), provide a new <code>Gson</code> instance with your desired behavior when building a <code>Retrofit</code>. Refer to the <a href="https://sites.google.com/site/gson/gson-user-guide">Gson documentation</a> for more details on customization.</p>
<h4>Custom Gson Converter Example</h4>
<p>The following code creates a new <code>Gson</code> instance that will convert all fields from lower case with underscores to camel case and vice versa. It also registers a type adapter for the <code>Date</code> class. This <code>DateTypeAdapter</code> will be used anytime Gson encounters a <code>Date</code> field.</p>
<p>The <code>gson</code> instance is passed as a parameter to <code>GsonConverter</code>, which is a wrapper class for converting types.</p>
<pre class="prettyprint">Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Date.class, new DateTypeAdapter())
.create();
Retrofit retrofit = new Retrofit.Builder()
.setEndpoint("https://api.github.com")
.setConverter(new GsonConverter(gson))
.build();
GitHubService service = retrofit.create(GitHubService.class);</pre>
<p>Each call on the generated <code>GithubService</code> will return objects converted using the Gson implementation provided to the <code>Retrofit</code>.</p>
<h4>Content format Agnostic</h4>
<p>In addition to JSON, Retrofit can be configured to use other content formats. Retrofit provides alternate converters for XML (using <a href="http://simple.sourceforge.net/">Simple</a>) and Protocol Buffers (using <a href="https://code.google.com/p/protobuf/">protobuf</a> or <a href="https://github.com/square/wire">Wire</a>). Please see the <a href="https://github.com/square/retrofit/tree/master/retrofit-converters">retrofit-converters</a> directory for the full listing of converters.</p>
<p>The following code shows how to use <code>SimpleXMLConverter</code> to communicate with an API that uses XML</p>
<pre class="prettyprint">Retrofit retrofit = new Retrofit.Builder()
.setEndpoint("https://api.soundcloud.com")
.setConverter(new SimpleXMLConverter())
.build();
SoundCloudService service = retrofit.create(SoundCloudService.class);</pre>
<h4>Custom Converters</h4>
<p>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 implements the <a href="https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit/Converter.java"><code>Converter</code> interface</a> and pass in an instance when building your adapter.</p>
<h4>Custom Error Handling</h4>
<p>If you need custom error handling for requests, you may provide your own <code>ErrorHandler</code>. The following code shows how to throw a custom exception when a response returns a HTTP 401 status code</p>
<pre class="prettyprint">
class MyErrorHandler implements ErrorHandler {
@Override public Throwable handleError(RetrofitError cause) {
Response r = cause.getResponse();
if (r != null && r.getStatus() == 401) {
return new UnauthorizedException(cause);
}
return cause;
}
}
Retrofit retrofit = new Retrofit.Builder()
.setEndpoint("https://api.github.com")
.setErrorHandler(new MyErrorHandler())
.build();</pre>
<p>Note that if the return exception is checked, it must be declared on the interface method. It is recommended that you pass the supplied <code>RetrofitError</code> as the cause to any new exceptions you throw.</p>
<h4>Logging</h4>
<p>If you need to take a closer look at the requests and responses you can easily add logging levels to the <code>Retrofit</code> with the <code>LogLevel</code> property. The possible logging levels are <code>BASIC</code>, <code>FULL</code>, <code>HEADERS</code>, and <code>NONE</code>.</p>
<p>The following code shows the addition of a full log level which will log the headers, body, and metadata for both requests and responses.</p>
<pre class="prettyprint">
Retrofit retrofit = new Retrofit.Builder()
.setLogLevel(Retrofit.LogLevel.FULL)
.setEndpoint("https://api.github.com")
.build();</pre>
<p>This logging can be added or changed at any point in the <code>Retrofit</code>'s lifecycle by calling the same <code>.setLogLevel()</code> method and supplying a different <code>LogLevel</code> value.</p>
<h3 id="download">Download</h3>
<p><a href="https://search.maven.org/remote_content?g=com.squareup.retrofit&a=retrofit&v=LATEST" class="dl version-href">↓ <span class="version-tag">Latest</span> JAR</a></p>
<p>The source code to the Retrofit, its samples, and this website is <a href="http://github.com/square/retrofit">available on GitHub</a>.</p>
<h4>Maven</h4>
<pre class="prettyprint"><dependency>
<groupId>com.squareup.retrofit</groupId>
<artifactId>retrofit</artifactId>
<version><span class="version pln"><em>(insert latest version)</em></span></version>
</dependency></pre>
<h4>Gradle</h4>
<pre class="prettyprint">
compile 'com.squareup.retrofit:retrofit:<span class="version pln"><em>(insert latest version)</em></span>'
</pre>
<p>Retrofit requires at minimum Java 7 or Android 2.3.</p>
<h4>Integration with OkHttp</h4>
<p>Retrofit will automatically use OkHttp (version 2.0 or newer) when it is present.</p>
<h4>Maven</h4>
<pre class="prettyprint"><dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version><span class="okhttpversion pln"><em>(insert latest version)</em></span></version>
</dependency>
</pre>
<h4>Gradle</h4>
<pre class="prettyprint">
compile 'com.squareup.okhttp:okhttp:<span class="okhttpversion pln"><em>(insert latest version)</em></span>'
</pre>
<h4>ProGuard</h4>
<p>If you are using Proguard in your project add the following lines to your configuration:</p>
<pre class="prettyprint">
-dontwarn retrofit.**
-keep class retrofit.** { *; }
-keepattributes Signature
-keepattributes Exceptions
</pre>
<h3 id="contributing">Contributing</h3>
<p>If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request.</p>
<p>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 <code>mvn clean verify</code>.</p>
<p>Before your code can be accepted into the project you must also sign the <a href="http://squ.re/sign-the-cla">Individual Contributor License Agreement (CLA)</a>.</p>
<h3 id="license">License</h3>
<pre>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.</pre>
</div>
<div class="span3">
<div class="content-nav" data-spy="affix" data-offset-top="80">
<ul class="nav nav-tabs nav-stacked primary">
<li><a href="#introduction">Introduction</a></li>
<li><a href="#api-declaration">API Declaration</a></li>
<li><a href="#restadapter-configuration">Retrofit Configuration</a></li>
<li><a href="#download">Download</a></li>
<li><a href="#contributing">Contributing</a></li>
<li><a href="#license">License</a></li>
</ul>
<ul class="nav nav-pills nav-stacked secondary">
<li><a href="javadoc/index.html">Javadoc</a></li>
<li><a href="http://stackoverflow.com/questions/tagged/retrofit?sort=active">StackOverflow</a></li>
</ul>
</div>
</div>
</div>
<div class="row">
<div class="span12 logo">
<a href="https://squareup.com"><img src="static/logo-square.png" alt="Square, Inc."/></a>
</div>
</div>
</div>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="static/bootstrap.min.js"></script>
<script src="static/jquery.smooth-scroll.min.js"></script>
<script src="static/jquery-maven-artifact.min.js"></script>
<script src="static/prettify.js"></script>
<script type="text/javascript">
$(function() {
// Syntax highlight code blocks.
prettyPrint();
// Spy on scroll position for real-time updating of current section.
$('body').scrollspy();
// Use smooth-scroll for internal links.
$('a').smoothScroll();
// Enable tooltips on the header nav image items.
$('.menu').tooltip({
placement: 'bottom',
trigger: 'hover',
container: 'body',
delay: {
show: 500,
hide: 0
}
});
// Look up the latest version of the library.
$.fn.artifactVersion('com.squareup.retrofit', 'retrofit', function(version, url) {
$('.version').text(version);
$('.version-tag').text('v' + version);
$('.version-href').attr('href', url);
});
$.fn.artifactVersion('com.squareup.okhttp', 'okhttp', function(version, url) {
$('.okhttpversion').text(version);
});
});
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-40704740-4', 'github.io');
ga('send', 'pageview');
</script>
</body>
</html>