参考: https://github.com/square/retrofit/blob/trunk/retrofit/kotlin-test/src/test/java/retrofit2/KotlinSuspendTest.kt
https://amitshekhar.me/blog/retrofit-with-kotlin-coroutines
Retrofit 2.6.0 版本引入了对挂起函数的原生支持,可以使用 suspend 修饰符来定义挂起函数,这使得在协程中使用 Retrofit 更加方便。在挂起函数中,您可以直接调用 Retrofit 的网络请求方法,而无需手动创建 Call 对象,并使用 enqueue 或 execute 方法来发起请求。示例如下:
import retrofit2.http.GET
import retrofit2.http.Path
// 定义 Retrofit 的 API 接口
interface ApiService {
@GET("users/{username}")
suspend fun getUser(@Path("username") username: String): User
}
// 使用 Retrofit 创建 API 接口的实例
val apiService = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
// 在挂起函数中直接调用 Retrofit 的网络请求方法
suspend fun getUser(username: String): User {
return apiService.getUser(username)
}
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface MyApiService {
@POST("your-endpoint-url")
Call<Void> postJson(@Body RequestBody json);
}
sendJson
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class YourClass {
private static final String BASE_URL = "https://your-api.com/";
private MyApiService apiService;
public YourClass() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiService = retrofit.create(MyApiService.class);
}
public void sendJson(String jsonString) {
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create(mediaType, jsonString);
Call<Void> call = apiService.postJson(requestBody);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
if (response.isSuccessful()) {
// 请求成功处理
System.out.println("JSON posted successfully");
} else {
// 请求失败处理
System.out.println("Failed to post JSON, error code: " + response.code());
}
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
// 请求网络失败处理
System.out.println("Failed to post JSON due to: " + t.getMessage());
}
});
}
}