Getting Started with Retrofit

If you have ever made a HTTP network call using async tasks, then you know how much code we need to write for the network operation. We also have to take care of memory, caches, etc. So to make life easier, we have some libraries that can simplify our task. Retrofit is one of the most popularly used libraries for this job.

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. In Retrofit, you configure which converter is used for the data serialization. Typically for JSON, you use GSon, but you can add custom converters to process XML or other protocols. Retrofit uses the OkHttp library for HTTP requests.

To work with Retrofit, you need basically three classes.

Table of Contents

  1. Model class which is used to map the JSON data
  2. Interfaces which defines the possible HTTP operations
  3. Retrofit.Builder class – Instance which uses the interface and the Builder API which allows defining the URL end point for the HTTP operation.


JSON response

[ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitaensequi sint nihil reprehenderit dolor beatae ea dolores nequenfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendisnqui aperiam non debitis possimus qui neque nisi nulla" }, { "userId": 1, "id": 3, "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut", "body": "et iusto sed quo iurenvoluptatem occaecati omnis eligendi aut adnvoluptatem doloribus vel accusantium quis pariaturnmolestiae porro eius odio et labore et velit aut" }, . . .

Create an Android ProjectLet’s get our hands dirty and create an Android Studio project. I’ve created mine and named it RetrofitLearn.

Add Internet Permission

Add this line of code to your manifest file above the application tag.

Add gradle dependencies

Adding libraries are very easy. You just need to add the following two lines inside the dependencies block of your app level build.gradle file.

Retrofit automatically serializes the JSON response using a POJO (Plain Old Java Object) which must be defined in advance for the JSON structure. To serialize JSON we need a converter to convert it into Gson first. That’s the reason we added (implementation ‘com.squareup.retrofit2:converter-gson:2.2.0’).

The Model Class To get this title, we have to name our String as title (case sensitive) in the model class.

If you put the annotation @SerializedName (“attribute title”) with the JSON attribute name just above every variable you are defining, you can name your variables anything. But, you have to put the correct attribute name inside SerializedName (“title”).

Note: the value title inside the SerializedName (“title”) is the same as the value “title” in the JSON response from the API.

Creating the API Interface To make an API call using Retrofit, we need a Java interface where we define all of the URLs with the HTTP request type and parameters. In this example, we need to perform an HTTP GET with no extra parameters. Let’s create a Java interface inside and name it

Displaying the Posts in a ListView

In the activity_main.xml of your project, create a ListView.

Fetching the JSON Data

Inside, write the following code:

public class MainActivity extends AppCompatActivity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(; setSupportActionBar(toolbar); listView = findViewById(; FloatingActionButton fab = findViewById(; fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); getPosts(); } private void getPosts(){ //Creating a retrofit obkect Retrofit retrofit = new Retrofit.Builder() .baseUrl(PostApi.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); //creating the postApi interface PostApi postApi = retrofit.create(PostApi.class); //making the call object Call<List> call = postApi.getPosts(); call.enqueue(new Callback<List>() { @Override public void onResponse(@NonNull Call<List> call, @NonNull Response<List> response) { List postList = response.body(); //Creating a String array for the Listview String[] posts = new String[postList.size()]; //looping through all the posts for (int i = 0; i < postList.size(); i++){ posts[i] = postList.get(i).getTitle(); } //displaying the string array into listview listView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, posts)); } @Override public void onFailure(Call<List> call, Throwable t) { Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == { return true; } return super.onOptionsItemSelected(item); }

Now you can run and test the app on an emulator or on a real device.

稿源:Codementor Tutorials (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » Getting Started with Retrofit

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录