How to Use Retrofit2 in Android for GET Data Queries and File Uploads

This guide walks through adding Retrofit2 to an Android project, configuring network permissions, creating a singleton WebClient, defining GET and multipart POST interfaces, and handling responses to display data in a ListView and upload files to a SpringBoot backend.

The Dominant Programmer
The Dominant Programmer
The Dominant Programmer
How to Use Retrofit2 in Android for GET Data Queries and File Uploads

Retrofit Overview

Retrofit is a type‑safe HTTP client for Android and Java that wraps OkHttp and is provided by Square. It simplifies HTTP communication.

Import Dependencies

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

After adding these lines to build.gradle, sync the project. Do not add OkHttp or Gson separately because Retrofit already includes them.

Network Permission

<uses-permission android:name="android.permission.INTERNET" />

Build a Singleton Http Client

Create a WebClient class that holds a single ApiService instance:

package com.badao.badaoimclient.web;

import android.util.Log;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class WebClient {
    private static ApiService INSTANCE;
    private static final String BASE_URL = "http://your-backend-ip:8000/";
    public static ApiService getInstance() {
        if (INSTANCE == null) {
            synchronized (ApiService.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
                        .create(ApiService.class);
                    Log.i("INSTANCE", BASE_URL);
                }
            }
        }
        return INSTANCE;
    }
}

The BASE_URL must end with a slash and point to the backend service.

Define the API Interface

package com.badao.badaoimclient.web;

import com.badao.badaoimclient.bean.ImUserBean;
import com.badao.badaoimclient.bean.UploadBean;
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public interface ApiService {
    // No‑parameter GET request
    @GET("system/imuser/listForApp")
    Call<ImUserBean> getImUserList();

    // File upload
    @Multipart
    @POST("/common/upload")
    Call<UploadBean> upload(@Part MultipartBody.Part file);
}

The interface provides one GET method that returns ImUserBean and one multipart POST method that returns UploadBean.

Data Model Example

package com.badao.badaoimclient.bean;

import com.google.gson.annotations.SerializedName;
import java.util.List;

public class ImUserBean {
    private int total;
    private int code;
    private Object msg;
    private List<RowsBean> rows;
    // getters and setters omitted for brevity
    public static class RowsBean {
        @SerializedName("id")
        private int idX;
        @SerializedName("imNum")
        private String imNumX;
        @SerializedName("canOnline")
        private int canOnlineX;
        // getters and setters omitted for brevity
    }
}

GET Request Usage

Invoke the GET API where data is needed:

WebClient.getInstance().getImUserList().enqueue(new Callback<ImUserBean>() {
    @Override
    public void onResponse(Call<ImUserBean> call, Response<ImUserBean> response) {
        Log.i("response", response.toString());
        if (response.code() == 200) {
            ImUserBean userBean = response.body();
            rowsBeanList = userBean.getRows();
            myAdapter = new MyAdapter(rowsBeanList);
            listView.setAdapter(myAdapter);
        }
    }
    @Override
    public void onFailure(Call<ImUserBean> call, Throwable t) {
        Log.i("onFailure", t.toString());
    }
});

The backend GET endpoint is implemented with SpringBoot:

@GetMapping("/listForApp")
@ResponseBody
public TableDataInfo listGet(ImUser imUser) {
    startPage();
    List<ImUser> list = imUserService.selectImUserList(imUser);
    return getDataTable(list);
}

When the request succeeds, the JSON response (shown in the article’s screenshots) is parsed into ImUserBean and displayed in a ListView via an adapter.

POST File Upload Usage

Add the multipart POST method to ApiService (already shown). Then upload a file:

RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
WebClient.getInstance().upload(part).enqueue(new Callback<UploadBean>() {
    @Override
    public void onResponse(Call<UploadBean> call, Response<UploadBean> response) {
        if (response.code() == 200) {
            chatItem.setRemoteContent(response.body().getFileName());
        } else {
            Toast.makeText(App.context, "Server returned " + response.code(), Toast.LENGTH_SHORT).show();
            return;
        }
    }
    @Override
    public void onFailure(Call<UploadBean> call, Throwable t) {
        Toast.makeText(App.context, t.toString(), Toast.LENGTH_SHORT).show();
    }
});

The SpringBoot backend handles the upload:

@PostMapping("/common/upload")
@ResponseBody
public AjaxResult uploadFile(MultipartFile file) throws Exception {
    try {
        String filePath = RuoYiConfig.getUploadPath();
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;
        AjaxResult ajax = AjaxResult.success();
        ajax.put("fileName", fileName);
        ajax.put("url", url);
        return ajax;
    } catch (Exception e) {
        return AjaxResult.error(e.getMessage());
    }
}

After a successful upload, the server returns a JSON object containing the new file name and URL, which the Android client can use (as illustrated in the article’s screenshots).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AndroidSpringBootOkHttpPOST uploadGET requestRetrofit2
The Dominant Programmer
Written by

The Dominant Programmer

Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.