在 Android Studio 中使用 API 调用,需要进行以下操作:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
public interface ApiService {
@GET("users/{username}")
Call getUser(@Path("username") String username, @Query("sort") String sort);
}
ApiService apiService = retrofit.create(ApiService.class);
Call call = apiService.getUser("user", "desc");
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
User user = response.body();
// 处理请求成功后的逻辑
}
@Override
public void onFailure(Call call