├── .gitignore
├── settings.gradle
├── README.md
├── artifactid.iml
└── src
└── main
└── java
├── Test.java
├── HttpApiSimple.java
└── HttpApi.java
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | build/
3 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'retrofit2-samples'
2 |
3 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Samples for Retrofit 2.0 (using http://httpbin.org)
2 |
3 | * https://github.com/metachris/retrofit2-samples/blob/master/src/main/java/Test.java
4 | * https://github.com/metachris/retrofit2-samples/blob/master/src/main/java/HttpApiSimple.java
5 | * https://github.com/metachris/retrofit2-samples/blob/master/src/main/java/HttpApi.java
6 |
7 |
8 | Links
9 |
10 | * http://square.github.io/retrofit/
11 | * http://square.github.io/retrofit/javadoc/index.html
12 | * http://inthecheesefactory.com/blog/retrofit-2.0/en
13 |
14 |
15 | License: MIT
16 |
17 | Feel free to add samples or request new ones!
18 |
19 | chris@metachris.org
20 |
21 |
--------------------------------------------------------------------------------
/artifactid.iml:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/src/main/java/Test.java:
--------------------------------------------------------------------------------
1 | import retrofit.Call;
2 | import retrofit.Callback;
3 | import retrofit.Response;
4 | import retrofit.Retrofit;
5 |
6 | import java.io.IOException;
7 |
8 | public class Test {
9 | public static void main(String[] args) {
10 | // HttpApiSimple.testApiRequest();;
11 | testInstance();
12 | }
13 |
14 | private static void testInstance() {
15 | // This can be used in any Activity, etc.
16 | HttpApi api = HttpApi.getInstance();
17 |
18 | // Add headers to be added to every api request
19 | api.addHeader("Authorization", "MyToken123");
20 |
21 | // Prepare the HTTP request & asynchronously execute HTTP request
22 | Call call = api.getService().postWithJson(new HttpApi.LoginData("username", "secret"));
23 | call.enqueue(new Callback() {
24 | /**
25 | * onResponse is called when any kind of response has been received.
26 | */
27 | public void onResponse(Response response, Retrofit retrofit) {
28 | // http response status code + headers
29 | System.out.println("Response status code: " + response.code());
30 |
31 | // isSuccess is true if response code => 200 and <= 300
32 | if (!response.isSuccess()) {
33 | // print response body if unsuccessful
34 | try {
35 | System.out.println(response.errorBody().string());
36 | } catch (IOException e) {
37 | // do nothing
38 | }
39 | return;
40 | }
41 |
42 | // if parsing the JSON body failed, `response.body()` returns null
43 | HttpApi.HttpBinResponse decodedResponse = response.body();
44 | if (decodedResponse == null) return;
45 |
46 | // at this point the JSON body has been successfully parsed
47 | System.out.println("Response (contains request infos):");
48 | System.out.println("- url: " + decodedResponse.url);
49 | System.out.println("- ip: " + decodedResponse.origin);
50 | System.out.println("- headers: " + decodedResponse.headers);
51 | System.out.println("- args: " + decodedResponse.args);
52 | System.out.println("- form params: " + decodedResponse.form);
53 | System.out.println("- json params: " + decodedResponse.json);
54 | }
55 |
56 | /**
57 | * onFailure gets called when the HTTP request didn't get through.
58 | * For instance if the URL is invalid / host not reachable
59 | */
60 | public void onFailure(Throwable t) {
61 | System.out.println("onFailure");
62 | System.out.println(t.getMessage());
63 | }
64 | });
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/HttpApiSimple.java:
--------------------------------------------------------------------------------
1 | import retrofit.*;
2 | import retrofit.http.*;
3 |
4 | import java.io.IOException;
5 | import java.util.Map;
6 |
7 | public class HttpApiSimple {
8 |
9 | public static final String API_URL = "http://httpbin.org";
10 |
11 | /**
12 | * Generic HttpBin.org Response Container
13 | */
14 | static class HttpBinResponse {
15 | // the request url
16 | String url;
17 |
18 | // the requester ip
19 | String origin;
20 |
21 | // all headers that have been sent
22 | Map headers;
23 |
24 | // url arguments
25 | Map args;
26 |
27 | // post form parameters
28 | Map form;
29 |
30 | // post body json
31 | Map json;
32 | }
33 |
34 | /**
35 | * Exemplary login data sent as JSON
36 | */
37 | static class LoginData {
38 | String username;
39 | String password;
40 |
41 | public LoginData(String username, String password) {
42 | this.username = username;
43 | this.password = password;
44 | }
45 | }
46 |
47 | /**
48 | * HttpBin.org service definition
49 | */
50 | public interface HttpBinService {
51 | @GET("/get")
52 | Call get();
53 |
54 | // request /get?testArg=...
55 | @GET("/get")
56 | Call getWithArg(
57 | @Query("testArg") String arg
58 | );
59 |
60 | // POST form encoded with form field params
61 | @FormUrlEncoded
62 | @POST("/post")
63 | Call postWithFormParams(
64 | @Field("field1") String field1
65 | );
66 |
67 | // POST form encoded with form field params
68 | @POST("/post")
69 | Call postWithJson(
70 | @Body LoginData loginData
71 | );
72 | }
73 |
74 | public static void testApiRequest() {
75 | // Retrofit setup
76 | Retrofit retrofit = new Retrofit.Builder()
77 | .baseUrl(API_URL)
78 | .addConverterFactory(GsonConverterFactory.create())
79 | .build();
80 |
81 | // Service setup
82 | HttpBinService service = retrofit.create(HttpBinService.class);
83 |
84 | // Prepare the HTTP request
85 | Call call = service.postWithJson(new LoginData("username", "secret"));
86 |
87 | // Asynchronously execute HTTP request
88 | call.enqueue(new Callback() {
89 | /**
90 | * onResponse is called when any kind of response has been received.
91 | */
92 | public void onResponse(Response response, Retrofit retrofit) {
93 | // http response status code + headers
94 | System.out.println("Response status code: " + response.code());
95 |
96 | // isSuccess is true if response code => 200 and <= 300
97 | if (!response.isSuccess()) {
98 | // print response body if unsuccessful
99 | try {
100 | System.out.println(response.errorBody().string());
101 | } catch (IOException e) {
102 | // do nothing
103 | }
104 | return;
105 | }
106 |
107 | // if parsing the JSON body failed, `response.body()` returns null
108 | HttpBinResponse decodedResponse = response.body();
109 | if (decodedResponse == null) return;
110 |
111 | // at this point the JSON body has been successfully parsed
112 | System.out.println("Response (contains request infos):");
113 | System.out.println("- url: " + decodedResponse.url);
114 | System.out.println("- ip: " + decodedResponse.origin);
115 | System.out.println("- headers: " + decodedResponse.headers);
116 | System.out.println("- args: " + decodedResponse.args);
117 | System.out.println("- form params: " + decodedResponse.form);
118 | System.out.println("- json params: " + decodedResponse.json);
119 | }
120 |
121 | /**
122 | * onFailure gets called when the HTTP request didn't get through.
123 | * For instance if the URL is invalid / host not reachable
124 | */
125 | public void onFailure(Throwable t) {
126 | System.out.println("onFailure");
127 | System.out.println(t.getMessage());
128 | }
129 | });
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/src/main/java/HttpApi.java:
--------------------------------------------------------------------------------
1 | import com.squareup.okhttp.Interceptor;
2 | import com.squareup.okhttp.OkHttpClient;
3 | import com.squareup.okhttp.Request;
4 | import retrofit.Call;
5 | import retrofit.Callback;
6 | import retrofit.GsonConverterFactory;
7 | import retrofit.Response;
8 | import retrofit.Retrofit;
9 | import retrofit.http.*;
10 |
11 | import java.io.IOException;
12 | import java.util.HashMap;
13 | import java.util.Map;
14 |
15 | public class HttpApi {
16 | public static final String API_URL = "http://httpbin.org";
17 |
18 | private static HttpApi instance = null;
19 | private Map headers = new HashMap();
20 | private HttpBinService service;
21 |
22 | /**
23 | * Generic HttpBin.org Response Container
24 | */
25 | public static class HttpBinResponse {
26 | // the request url
27 | String url;
28 |
29 | // the requester ip
30 | String origin;
31 |
32 | // all headers that have been sent
33 | Map headers;
34 |
35 | // url arguments
36 | Map args;
37 |
38 | // post form parameters
39 | Map form;
40 |
41 | // post body json
42 | Map json;
43 | }
44 |
45 | /**
46 | * Exemplary login data sent as JSON
47 | */
48 | public static class LoginData {
49 | String username;
50 | String password;
51 |
52 | public LoginData(String username, String password) {
53 | this.username = username;
54 | this.password = password;
55 | }
56 | }
57 |
58 | /**
59 | * HttpBin.org service definition
60 | */
61 | public interface HttpBinService {
62 | @GET("/get")
63 | Call get();
64 |
65 | // request /get?testArg=...
66 | @GET("/get")
67 | Call getWithArg(
68 | @Query("testArg") String arg
69 | );
70 |
71 | // POST form encoded with form field params
72 | @FormUrlEncoded
73 | @POST("/post")
74 | Call postWithFormParams(
75 | @Field("field1") String field1
76 | );
77 |
78 | // POST form encoded with form field params
79 | @POST("/post")
80 | Call postWithJson(
81 | @Body LoginData loginData
82 | );
83 | }
84 |
85 | /**
86 | * Private constructor
87 | */
88 | private HttpApi() {
89 | // Http interceptor to add custom headers to every request
90 | OkHttpClient httpClient = new OkHttpClient();
91 | httpClient.networkInterceptors().add(new Interceptor() {
92 | public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
93 | Request.Builder builder = chain.request().newBuilder();
94 |
95 | System.out.println("Adding headers:" + headers);
96 | for (Map.Entry entry : headers.entrySet()) {
97 | builder.addHeader(entry.getKey(), entry.getValue());
98 | }
99 |
100 | return chain.proceed(builder.build());
101 | }
102 | });
103 |
104 | // Retrofit setup
105 | Retrofit retrofit = new Retrofit.Builder()
106 | .baseUrl(API_URL)
107 | .client(httpClient)
108 | .addConverterFactory(GsonConverterFactory.create())
109 | .build();
110 |
111 | // Service setup
112 | service = retrofit.create(HttpBinService.class);
113 | }
114 |
115 | /**
116 | * Get the HttpApi singleton instance
117 | */
118 | public static HttpApi getInstance() {
119 | if(instance == null) {
120 | instance = new HttpApi();
121 | }
122 | return instance;
123 | }
124 |
125 | /**
126 | * Get the API service to execute calls with
127 | */
128 | public HttpBinService getService() {
129 | return service;
130 | }
131 |
132 | /**
133 | * Add a header which is added to every API request
134 | */
135 | public void addHeader(String key, String value) {
136 | headers.put(key, value);
137 | }
138 |
139 | /**
140 | * Add multiple headers
141 | */
142 | public void addHeaders(Map headers) {
143 | this.headers.putAll(headers);
144 | }
145 |
146 | /**
147 | * Remove a header
148 | */
149 | public void removeHeader(String key) {
150 | headers.remove(key);
151 | }
152 |
153 | /**
154 | * Remove all headers
155 | */
156 | public void clearHeaders() {
157 | headers.clear();
158 | }
159 |
160 | /**
161 | * Get all headers
162 | */
163 | public Map getHeaders() {
164 | return headers;
165 | }
166 | }
167 |
--------------------------------------------------------------------------------