在app级别build.gradle文件中添加以下代码:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1'
}
在您的项目中创建一个API接口,该接口将定义在您的Android应用程序和Laravel网页之间发送的数据。例如:
interface ApiInterface {
@POST("api/user/create")
fun createUser(
@Field("name") name: String,
@Field("email") email: String,
@Field("password") password: String
): Call
}
在您的应用程序中,创建一个Retrofit实例,将其与您的Laravel网页URL链接,如下所示:
val retrofit = Retrofit.Builder()
.baseUrl("http://your-laravel-website.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(OkHttpClient.Builder().addInterceptor(HttpLoggingInterceptor()).build()) //此行代码可选,用于logging
.build()
创建一个实例并调用API方法,其中包含要发送到Laravel网页的数据。例如:
val apiInterface = retrofit.create(ApiInterface::class.java)
val call = apiInterface.createUser(name, email, password)
call.enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
//处理响应
}
override fun onFailure(call: Call, t: Throwable) {
//处理异常
}
})