如何正确执行以下带@GET注解的Retrofit请求代码片段?
Hey there! Let's walk through how to properly execute that Retrofit GET request step by step. I'll break it down clearly so you can follow along easily.
Before writing any code, you need to add the necessary dependencies to your project. Open your module-level build.gradle (or build.gradle.kts if you're using Kotlin) and add these lines:
dependencies { // Retrofit core library implementation 'com.squareup.retrofit2:retrofit:2.9.0' // Gson converter to parse JSON responses into your ImgRepo objects implementation 'com.squareup.retrofit2:converter-gson:2.9.0' }
Note: You can use a newer version of Retrofit if you prefer—just check the latest stable release.
ImgRepo Data Class Is Correct This class needs to mirror the structure of the JSON objects returned by your API. For example, if your API returns comments with fields like id, image_url, and content, your ImgRepo should look like this:
import com.google.gson.annotations.SerializedName; public class ImgRepo { private int id; // Use @SerializedName if your JSON field name doesn't match the class variable name @SerializedName("image_url") private String imageUrl; private String content; // Required: Gson needs a no-argument constructor public ImgRepo() {} // Getters and setters (or use Lombok to auto-generate them) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
Put the code you provided into a dedicated interface class (e.g., ApiService.java):
import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import java.util.ArrayList; public interface ApiService { @GET("comments?_sort=id&_order=desc&_limit=5&_page={pageNumber}") Call<ArrayList<ImgRepo>> fetchNewData(@Path("pageNumber") int pageNumber); }
Quick tip: Instead of hardcoding query parameters in the URL, you can use @Query for more flexibility. Here's an alternative version that does the same thing but is easier to adjust later:
@GET("comments") Call<ArrayList<ImgRepo>> fetchNewData( @Query("_sort") String sort, @Query("_order") String order, @Query("_limit") int limit, @Query("_page") int pageNumber ); // When calling it: fetchNewData("id", "desc", 5, 1)
Now comes the core part—creating the Retrofit client, getting your service proxy, and firing off the request. We'll cover both asynchronous (recommended for Android to avoid blocking the main thread) and synchronous (for non-UI threads or non-Android environments) approaches:
Asynchronous Request (Android Recommended)
// 1. Build the Retrofit instance with your API base URL Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://your-api-base-url.com/") // Replace with your actual base URL (must end with /) .addConverterFactory(GsonConverterFactory.create()) .build(); // 2. Create a proxy instance of your ApiService ApiService apiService = retrofit.create(ApiService.class); // 3. Create the call object with your desired page number (e.g., page 1) Call<ArrayList<ImgRepo>> call = apiService.fetchNewData(1); // 4. Enqueue the call to execute it asynchronously call.enqueue(new Callback<ArrayList<ImgRepo>>() { @Override public void onResponse(Call<ArrayList<ImgRepo>> call, Response<ArrayList<ImgRepo>> response) { if (response.isSuccessful()) { // Request succeeded! Get the data from the response body ArrayList<ImgRepo> imgRepos = response.body(); // Handle the data here—like updating your UI (make sure this runs on the main thread) if (imgRepos != null) { // Do something with your list of ImgRepo objects } } else { // Request went through but returned an error code (e.g., 404, 500) try { String errorDetails = response.errorBody().string(); // Handle the error details } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFailure(Call<ArrayList<ImgRepo>> call, Throwable t) { // Request failed entirely (e.g., no internet connection) String errorMessage = t.getMessage(); // Handle the failure (show a toast, log the error, etc.) } });
Synchronous Request (Only Use in Background Threads)
If you're working in a background thread (like a Kotlin coroutine, Java Thread, or AsyncTask), you can use synchronous execution:
// Build Retrofit and ApiService same as before Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://your-api-base-url.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); ApiService apiService = retrofit.create(ApiService.class); try { Call<ArrayList<ImgRepo>> call = apiService.fetchNewData(1); // Execute the call synchronously Response<ArrayList<ImgRepo>> response = call.execute(); if (response.isSuccessful()) { ArrayList<ImgRepo> imgRepos = response.body(); // Process your data } else { // Handle error response } } catch (IOException e) { e.printStackTrace(); // Handle IO exceptions (network errors, etc.) }
- Base URL Must Be Correct: Ensure your base URL is the root of your API. For example, if your full request URL is
https://jsonplaceholder.typicode.com/comments?_sort=id&..., your base URL should behttps://jsonplaceholder.typicode.com/. - Android Internet Permission: Don't forget to add this to your
AndroidManifest.xml:<uses-permission android:name="android.permission.INTERNET" /> - Thread Safety: Never run synchronous requests on the Android main thread—this will throw a
NetworkOnMainThreadException. Always use asynchronous requests or move synchronous calls to a background thread. - Field Matching: Make sure your
ImgRepoclass fields match the JSON response fields exactly (case-sensitive). If they don't, use the@SerializedNameannotation to map them correctly.
内容的提问来源于stack exchange,提问作者Nzo

