net*_*000 5 rest kotlin retrofit
我正在尝试使用Kotlin和Retrofit进行POST请求,其中我只对请求的状态代码感兴趣.我已经看过的教程解决了一下,大多数时候它们不再编译或者非常复杂.
有人可以帮助改进此代码:?
interface ClientService {
@POST("user/password-reset")
fun passwortReset(@Query("email") email: String): Observable<Result>
companion object {
fun create(): ClientService {
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://test-backend.myurl.com/api/")
.build()
return retrofit.create(ClientService::class.java)
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何调用它以及如何获取状态代码.
Aru*_*run 10
试试这个例子
在build.gradle下:
// retrofit
compile "com.squareup.retrofit2:retrofit:2.3.0"
compile "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
compile "com.squareup.retrofit2:converter-gson:2.3.0"
// rxandroid
compile "io.reactivex.rxjava2:rxandroid:2.0.1"
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
Run Code Online (Sandbox Code Playgroud)
接口:
interface APIService {
@POST("register")
@FormUrlEncoded
fun registrationPost(@Field("email") email: String,
@Field("password") password: String): Call<Registration>}
//**App Utils**
object ApiUtils {
val BASE_URL = "your_url"
val apiService: APIService
get() = RetrofitClient.getClient(BASE_URL)!!.create(APIService::class.java)
}
Run Code Online (Sandbox Code Playgroud)
改造客户:
object RetrofitClient {
var retrofit: Retrofit? = null
fun getClient(baseUrl: String): Retrofit? {
if (retrofit == null) {
//TODO While release in Google Play Change the Level to NONE
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.addInterceptor(interceptor)
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100, TimeUnit.SECONDS)
.build()
retrofit = Retrofit.Builder()
.client(client)
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit
}
}
Run Code Online (Sandbox Code Playgroud)
主要活动
//Variable declaration
var mAPIService: APIService? = null
//After oncreate
mAPIService = ApiUtils.apiService
//Some Button click
mAPIService!!.registrationPost("SampleTest2@gamil.com", "123456").enqueue(object : Callback<Registration> {
override fun onResponse(call: Call<Registration>, response: Response<Registration>) {
Log.i("", "post submitted to API." + response.body()!!)
if (response.isSuccessful()) {
Log.i("", "post registration to API" + response.body()!!.toString())
Log.i("", "post status to API" + response.body()!!.status)
Log.i("", "post msg to API" + response.body()!!.messages)
}
}
override fun onFailure(call: Call<Registration>, t: Throwable) {
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11542 次 |
| 最近记录: |