我想将用户注册到我们公司的后端服务器。
为此,我创建了一个带有api键的@Header和带有用户信息的@Body的Post请求。但是,当我按下api时,作为响应,它会显示类似“ data”:[]的响应,其中应该像“ data”:{}
SignInInfo.kt
data class SignInInfo(
@SerializedName("name") val name: String,
@SerializedName("email") val email: String,
@SerializedName("user_type") val userType: String,
@SerializedName("phone") val phone: String,
@SerializedName("password") val password: String
)
RegistrationResponse.kt
data class RegistrationResponse(
@field:SerializedName("msg") val msg: String? = null,
@field:SerializedName("data") val data: Data? = null,
@field:SerializedName("status") val status: Int? = null
)
Data.kt
data class Data(
@field:SerializedName("user_id") val userId: Int,
@field:SerializedName("id") val id: Int,
@field:SerializedName("token") val token: String
)
api.kt
@POST(Constants.API_USER_REGISTRATION)
fun registerUser(
@Body signInInfo: SignInInfo
): Call<RegistrationResponse>
RetrofitBuilder.kt
object RetrofitBuilder {
fun retrofit(baseUrl: String): Retrofit = Retrofit.Builder()
.client(getOkHttpClient())
.baseUrl(baseUrl)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
private fun getOkHttpClient(): OkHttpClient {
return OkHttpClient().newBuilder()
.connectTimeout(3, TimeUnit.SECONDS)
.readTimeout(3, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS)
.addInterceptor(headersInterceptor)
.addInterceptor(loggingInterceptor)
.build()
}
}
ApiUtils.kt
object ApiUtils {
val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
val headersInterceptor = Interceptor {
val request = it.request()
it.proceed(
request.newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json")
.addHeader("api_key", "sr8fyw8hcow8efhisncsef0wefw9ef0swdcsopd")
.build()
)
}
}
viewModel.kt
fun register(signInInfo: SignInInfo) {
ApiFactory.userRegistrationApi.registerUser(signInInfo).enqueue(object :
Callback<RegistrationResponse> {
override fun onFailure(call: Call<RegistrationResponse>, t: Throwable) {
Log.d("Got Error Here", t.toString())
}
override fun onResponse(
call: Call<RegistrationResponse>,
response: Response<RegistrationResponse>
) {
if (response.isSuccessful) {
Log.d("Success", response.body()?.msg)
} else {
Log.d("error", response.message())
}
}
})
}
我希望这样的输出
{
"status": 1,
"data": {
"id": 135386,
"user_id": 1567057386,
"token": "geYs2rO6wjtO653I9OVhJWTFwYxAvnYnLGG7wm7dfa"
},
"msg": "Welcome Aomi"
}