This tutorial explains the usage of the Retrofit library as REST client.
- What is Retrofit?
Retrofit is a REST Client for Android and Java by Square. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice. - Using Retrofit
To work with Retrofit you need basically three classes. - Model class which is used to map the JSON data to
- Interfaces which defines the possible HTTP operations
- Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL end point for the HTTP operation.
Every method of an interface represents one possible API call. It must have a HTTP annotation (GET, POST, etc.) to specify the request type and the relative URL. The return value wraps the response in a Call object with the type of the expected result.
Add these two lines to the build.gradle file:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
Also Add Internet permission to AndroidManifest.xml file
Retrofit turns your HTTP API into a Java interface.
<uses-permission
android:name="android.permission.INTERNET" />
Retrofit turns your HTTP API into a Java interface.
public interface ApiClientListener {@FormUrlEncoded@POST("/login/") Call<Login> login(@Field("email") String email, @Field("password") String password); }The Retrofit class generates an implementation of the interface.Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); Calling login APIApiClientListener apiClientListener = retrofit.create(ApiClientListener.class);Call<Login> call = apiClientListener.login("email", "password");call.enqueue(new Callback<Login>() { @Override public void onResponse(Call<Login> call, Response<Login> response) { // Success } @Override public void onFailure(Call<Login> call, Throwable t) { // Error } }); }
Sunrise Technologies builds secure, scalable, and intelligent solutions tailored to your organisation’s unique needs. From process automation to system integration, we help Australian enterprises drive efficiency and innovation with future-ready technology.
ReplyDeleteE-commerce Software Developer in Australia
Budgeting for custom software in 2025? This guide reveals all the hidden costs and smart saving strategies. Must-read for CTOs! Discover more in the A Complete Guide to the Software Development Cost 2025
ReplyDeleteAI-driven money management apps that help users save, invest, and track expenses. Integrations with Plaid, Stripe & Xero. Perfect for fintech innovators. Start developing today!
ReplyDeleteApp Developers Brisbane
From idea to App Store—we turn your vision into reality.
ReplyDelete👉 Learn more: iOS Mobile App Development Company Sydney