用改造和GSON解析API时空的响应主体

发布于 2025-02-10 18:04:55 字数 9721 浏览 1 评论 0原文

我在这个项目上使用了Retrofit和Gson。我正在尝试登录应该获取用户ID,FAUNADB_TOKEN以及填充用户数据的数据列表的响应。

"body": "{\n    \"content\": {\n        \"id\": \"328803596056396364\",\n        \"faunadb_token\": \"fauna fnEEnk81KUACTwSP8HIOwApJqbjNg-u4fqC9q6Da2FvPTP2esYs\",\n        \"data\": {\n            \"name\": \"test2\",\n            \"email\": \"[email protected]\",\n            \"role\": \"admin\",\n            \"organization_id\": \"328992226856141394\",\n            \"address\": \"address local\",\n            \"birthdate\": \"2000-04-13\",\n            \"phonenumber\": \"0811033222\",\n            \"s3_image\": \"https://assignmentsystem.s3.ap-southeast-1.amazonaws.com/userimages/0abf8e6b-c2b2-4e49-9a88-10ffb3fffaba-272327.jpg\"\n        }\n    },\n    \"message\": \"Successful Login\",\n    \"errors\": []\n}"

但是,当我登录时,我的状态代码为200,但我的响应。Body都是无效的。为了测试目的,我创建一个文本视图以查看响应是什么。

Screenshot of response.body returns null

But, in the terminal I can see that the actual response body is there, I just don知道如何获得该(第三行)。

I/okhttp.OkHttpClient: <-- 200 https://api.absensia.online/backend/user/login (1111ms)
I/okhttp.OkHttpClient: content-type: application/json; charset=utf-8
I/okhttp.OkHttpClient: x-powered-by: Express
I/okhttp.OkHttpClient: access-control-allow-origin: *
I/okhttp.OkHttpClient: etag: W/"1b0-6FklyrUjQI2dIrZLhEXcT1rvf1A"
I/okhttp.OkHttpClient: vary: Accept-Encoding
I/okhttp.OkHttpClient: date: Mon, 27 Jun 2022 07:45:02 GMT
I/okhttp.OkHttpClient: x-kong-upstream-latency: 264
I/okhttp.OkHttpClient: x-kong-proxy-latency: 1
I/okhttp.OkHttpClient: via: kong/2.8.1
I/okhttp.OkHttpClient: {"content":{"id":"328803596056396364","faunadb_token":"fauna fnEEqE4wt-ACUQSP8HIOwApJ7n1pLvPWUfBNciPtrEL0t1ifoT8","data":{"name":"test2","email":"[email protected]","role":"admin","organization_id":"328992226856141394","address":"address local","birthdate":"2000-04-13","phonenumber":"0811033222","s3_image":"https://assignmentsystem.s3.ap-southeast-1.amazonaws.com/userimages/default.png"}},"message":"Successful Login","errors":[]}
I/okhttp.OkHttpClient: <-- END HTTP (432-byte body)
D/EGL_emulation: app_time_stats: avg=16.10ms min=1.92ms max=565.09ms count=42

Here are some of my code:

ApiConfig

object ApiConfig {
    private const val BASE_URL = "https://api.absensia.online/backend/"
    private val client: Retrofit
        get() {
            val gson = GsonBuilder().setLenient().create()

            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY

            val client: OkHttpClient = OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .connectTimeout(40, TimeUnit.SECONDS)
                .readTimeout(40, TimeUnit.SECONDS)
                .writeTimeout(40, TimeUnit.SECONDS)
                .build()

            return Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build()
        }

    val instanceRetrofit: ApiService
        get() = client.create(ApiService::class.java)
}

ApiService

interface ApiService {

    @FormUrlEncoded
    @POST("user/login")
    suspend fun login(
        @Field("email") email:String,
        @Field("password") password:String,
    ): Response<LoginResponse>

    @GET("user/logout")
    suspend fun logout(
        @Header("Auth") auth: String
    ): Response<ResponseAuth>

}

LoginResponse class

data class LoginResponse(

    @SerializedName("id")
    var id: String?,

    @SerializedName("faunadb_token")
    var faunadb_token: String?,

    @SerializedName("data")
    var data: User?
)

Repository

class Repository {

    suspend fun login(email: String, password: String): Response<LoginResponse>{
        return ApiConfig.instanceRetrofit.login(email, password)
    }

    suspend fun logout(auth: String): Response<ResponseAuth>{
        return ApiConfig.instanceRetrofit.logout(auth)
    }
}

AuthenticationViewModel

class AuthenticationViewModel(private val repository: Repository): ViewModel() {

    var loginResponse: MutableLiveData<Response<LoginResponse>> = MutableLiveData()
    var logout: MutableLiveData<Response<ResponseAuth>> = MutableLiveData()

    fun login(email: String, password: String){
        viewModelScope.launch {
            val response = repository.login(email, password)
            loginResponse.value = response
        }
    }

    fun logout(auth: String){
        viewModelScope.launch {
            val response = repository.logout(auth)
            logout.value = response
        }
    }

}

AuthenticationViewModelFactory

class AuthenticationViewModelFactory(private val repository: Repository): ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return AuthenticationViewModel(repository) as T
    }

}

LoginActivity

class LoginActivity : AppCompatActivity() {

    private lateinit var loginpref: SharedPref
    private lateinit var viewModel: AuthenticationViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_masuk)
        loginpref = SharedPref(this)

        val masuk = findViewById<Button>(R.id.masuk_btn)
        masuk.setOnClickListener {
            masukButton()
        }

        buttonsMasukTest()
    }

    private fun masukButton(){
        val masukEmail = findViewById<TextInputEditText>(R.id.masukHpEmail)
        val masukPass = findViewById<TextInputEditText>(R.id.masukPass)

        val masukEmailLayout = findViewById<TextInputLayout>(R.id.masukHpEmail_layout)
        val masukPassLayout = findViewById<TextInputLayout>(R.id.masukPass_layout)

        val loadMasuk = findViewById<ProgressBar>(R.id.load_masuk)

        masukEmailLayout.isErrorEnabled = false
        masukPassLayout.isErrorEnabled = false

        if (masukEmail.text.toString().isEmpty()) {
            masukEmailLayout.isErrorEnabled = true
            masukEmailLayout.error = "Mohon mengisi kolom ini"
            masukEmailLayout.requestFocus()
            return
        }
        if (masukPass.text.toString().isEmpty()) {
            masukPassLayout.isErrorEnabled = true
            masukPassLayout.error = "Mohon mengisi kolom ini"
            masukPassLayout.requestFocus()
            return
        }
        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(masukEmail.text.toString()).matches()){
                masukEmailLayout.isErrorEnabled = true
                masukEmailLayout.error = "Mohon mengisi email dengan benar"
                masukEmailLayout.requestFocus()
                return
        }

        loadMasuk.visibility = View.VISIBLE

        val repository = Repository()
        val viewModelFactory = AuthenticationViewModelFactory(repository)
        viewModel = ViewModelProvider(this, viewModelFactory).get(AuthenticationViewModel::class.java)
        viewModel.login(
            masukEmail.text.toString(),
            masukPass.text.toString())
        viewModel.loginResponse.observe(this, Observer { response ->
            if (response.isSuccessful){
                loadMasuk.visibility = View.GONE

                val respon = response.body()

                loginpref.setStatusLogin(true)

                respon?.data?.let { loginpref.setUser(it) }
                respon?.faunadb_token?.let { loginpref.saveToken(it) }

                /**
                 * Momentary textview so I can know my respon
                 */
                findViewById<TextView>(R.id.testing).setText(respon.toString())

                /**
                 * I comment the section where it start the next activity for testing purposes
                 */
//                val intent = Intent(this@LoginActivity, MainActivity::class.java)
//                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
//                startActivity(intent)
//                finish()
//                Toast.makeText(this@LoginActivity, "Welcome " + masukEmail.text.toString(), Toast.LENGTH_SHORT).show()


            }else if(!response.isSuccessful){
                loadMasuk.visibility = View.GONE
                Toast.makeText(this@LoginActivity, "Login failed: Your Email or Password is Incorrect : "+response, Toast.LENGTH_SHORT).show()
            }
        })

    }

    private fun buttonsMasukTest(){
        val testMasuk = findViewById<Button>(R.id.masuk_btnTest)

        testMasuk.setOnClickListener {
            val intent = Intent (this@LoginActivity, MainActivity::class.java)
            loginpref.setStatusLogin(true)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
            finish()
        }
    }
}

I'm new with Kotlin, I tried to read and watch from several sources regarding Okhttp, retrofit, gson, and viewmodel but with no avail in solving the issue.关于我如何获得响应主体的任何帮助和建议将不胜感激。谢谢。

I used Retrofit and Gson on this project. I'm trying to login where I should get a response of the user id, faunadb_token, and also data list filled with user data.

"body": "{\n    \"content\": {\n        \"id\": \"328803596056396364\",\n        \"faunadb_token\": \"fauna fnEEnk81KUACTwSP8HIOwApJqbjNg-u4fqC9q6Da2FvPTP2esYs\",\n        \"data\": {\n            \"name\": \"test2\",\n            \"email\": \"[email protected]\",\n            \"role\": \"admin\",\n            \"organization_id\": \"328992226856141394\",\n            \"address\": \"address local\",\n            \"birthdate\": \"2000-04-13\",\n            \"phonenumber\": \"0811033222\",\n            \"s3_image\": \"https://assignmentsystem.s3.ap-southeast-1.amazonaws.com/userimages/0abf8e6b-c2b2-4e49-9a88-10ffb3fffaba-272327.jpg\"\n        }\n    },\n    \"message\": \"Successful Login\",\n    \"errors\": []\n}"

However, when I'm logging in, I got a statusCode of 200, yet my response.body is all null. For testing purposes, I create a textview to see what the response is.

Screenshot of response.body returns null

But, in the terminal I can see that the actual response body is there, I just don't know how to get that(Third line from bottom).

I/okhttp.OkHttpClient: <-- 200 https://api.absensia.online/backend/user/login (1111ms)
I/okhttp.OkHttpClient: content-type: application/json; charset=utf-8
I/okhttp.OkHttpClient: x-powered-by: Express
I/okhttp.OkHttpClient: access-control-allow-origin: *
I/okhttp.OkHttpClient: etag: W/"1b0-6FklyrUjQI2dIrZLhEXcT1rvf1A"
I/okhttp.OkHttpClient: vary: Accept-Encoding
I/okhttp.OkHttpClient: date: Mon, 27 Jun 2022 07:45:02 GMT
I/okhttp.OkHttpClient: x-kong-upstream-latency: 264
I/okhttp.OkHttpClient: x-kong-proxy-latency: 1
I/okhttp.OkHttpClient: via: kong/2.8.1
I/okhttp.OkHttpClient: {"content":{"id":"328803596056396364","faunadb_token":"fauna fnEEqE4wt-ACUQSP8HIOwApJ7n1pLvPWUfBNciPtrEL0t1ifoT8","data":{"name":"test2","email":"[email protected]","role":"admin","organization_id":"328992226856141394","address":"address local","birthdate":"2000-04-13","phonenumber":"0811033222","s3_image":"https://assignmentsystem.s3.ap-southeast-1.amazonaws.com/userimages/default.png"}},"message":"Successful Login","errors":[]}
I/okhttp.OkHttpClient: <-- END HTTP (432-byte body)
D/EGL_emulation: app_time_stats: avg=16.10ms min=1.92ms max=565.09ms count=42

Here are some of my code:

ApiConfig

object ApiConfig {
    private const val BASE_URL = "https://api.absensia.online/backend/"
    private val client: Retrofit
        get() {
            val gson = GsonBuilder().setLenient().create()

            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY

            val client: OkHttpClient = OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .connectTimeout(40, TimeUnit.SECONDS)
                .readTimeout(40, TimeUnit.SECONDS)
                .writeTimeout(40, TimeUnit.SECONDS)
                .build()

            return Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build()
        }

    val instanceRetrofit: ApiService
        get() = client.create(ApiService::class.java)
}

ApiService

interface ApiService {

    @FormUrlEncoded
    @POST("user/login")
    suspend fun login(
        @Field("email") email:String,
        @Field("password") password:String,
    ): Response<LoginResponse>

    @GET("user/logout")
    suspend fun logout(
        @Header("Auth") auth: String
    ): Response<ResponseAuth>

}

LoginResponse class

data class LoginResponse(

    @SerializedName("id")
    var id: String?,

    @SerializedName("faunadb_token")
    var faunadb_token: String?,

    @SerializedName("data")
    var data: User?
)

Repository

class Repository {

    suspend fun login(email: String, password: String): Response<LoginResponse>{
        return ApiConfig.instanceRetrofit.login(email, password)
    }

    suspend fun logout(auth: String): Response<ResponseAuth>{
        return ApiConfig.instanceRetrofit.logout(auth)
    }
}

AuthenticationViewModel

class AuthenticationViewModel(private val repository: Repository): ViewModel() {

    var loginResponse: MutableLiveData<Response<LoginResponse>> = MutableLiveData()
    var logout: MutableLiveData<Response<ResponseAuth>> = MutableLiveData()

    fun login(email: String, password: String){
        viewModelScope.launch {
            val response = repository.login(email, password)
            loginResponse.value = response
        }
    }

    fun logout(auth: String){
        viewModelScope.launch {
            val response = repository.logout(auth)
            logout.value = response
        }
    }

}

AuthenticationViewModelFactory

class AuthenticationViewModelFactory(private val repository: Repository): ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return AuthenticationViewModel(repository) as T
    }

}

LoginActivity

class LoginActivity : AppCompatActivity() {

    private lateinit var loginpref: SharedPref
    private lateinit var viewModel: AuthenticationViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_masuk)
        loginpref = SharedPref(this)

        val masuk = findViewById<Button>(R.id.masuk_btn)
        masuk.setOnClickListener {
            masukButton()
        }

        buttonsMasukTest()
    }

    private fun masukButton(){
        val masukEmail = findViewById<TextInputEditText>(R.id.masukHpEmail)
        val masukPass = findViewById<TextInputEditText>(R.id.masukPass)

        val masukEmailLayout = findViewById<TextInputLayout>(R.id.masukHpEmail_layout)
        val masukPassLayout = findViewById<TextInputLayout>(R.id.masukPass_layout)

        val loadMasuk = findViewById<ProgressBar>(R.id.load_masuk)

        masukEmailLayout.isErrorEnabled = false
        masukPassLayout.isErrorEnabled = false

        if (masukEmail.text.toString().isEmpty()) {
            masukEmailLayout.isErrorEnabled = true
            masukEmailLayout.error = "Mohon mengisi kolom ini"
            masukEmailLayout.requestFocus()
            return
        }
        if (masukPass.text.toString().isEmpty()) {
            masukPassLayout.isErrorEnabled = true
            masukPassLayout.error = "Mohon mengisi kolom ini"
            masukPassLayout.requestFocus()
            return
        }
        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(masukEmail.text.toString()).matches()){
                masukEmailLayout.isErrorEnabled = true
                masukEmailLayout.error = "Mohon mengisi email dengan benar"
                masukEmailLayout.requestFocus()
                return
        }

        loadMasuk.visibility = View.VISIBLE

        val repository = Repository()
        val viewModelFactory = AuthenticationViewModelFactory(repository)
        viewModel = ViewModelProvider(this, viewModelFactory).get(AuthenticationViewModel::class.java)
        viewModel.login(
            masukEmail.text.toString(),
            masukPass.text.toString())
        viewModel.loginResponse.observe(this, Observer { response ->
            if (response.isSuccessful){
                loadMasuk.visibility = View.GONE

                val respon = response.body()

                loginpref.setStatusLogin(true)

                respon?.data?.let { loginpref.setUser(it) }
                respon?.faunadb_token?.let { loginpref.saveToken(it) }

                /**
                 * Momentary textview so I can know my respon
                 */
                findViewById<TextView>(R.id.testing).setText(respon.toString())

                /**
                 * I comment the section where it start the next activity for testing purposes
                 */
//                val intent = Intent(this@LoginActivity, MainActivity::class.java)
//                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
//                startActivity(intent)
//                finish()
//                Toast.makeText(this@LoginActivity, "Welcome " + masukEmail.text.toString(), Toast.LENGTH_SHORT).show()


            }else if(!response.isSuccessful){
                loadMasuk.visibility = View.GONE
                Toast.makeText(this@LoginActivity, "Login failed: Your Email or Password is Incorrect : "+response, Toast.LENGTH_SHORT).show()
            }
        })

    }

    private fun buttonsMasukTest(){
        val testMasuk = findViewById<Button>(R.id.masuk_btnTest)

        testMasuk.setOnClickListener {
            val intent = Intent (this@LoginActivity, MainActivity::class.java)
            loginpref.setStatusLogin(true)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
            finish()
        }
    }
}

I'm new with Kotlin, I tried to read and watch from several sources regarding Okhttp, retrofit, gson, and viewmodel but with no avail in solving the issue. Any help and advice would be appreciated regarding how I can get the response body. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

颜漓半夏 2025-02-17 18:04:55
@FormUrlEncoded
@POST("user/login")
suspend fun login(
    @Field("email") email:String,
    @Field("password") password:String,
): Response<ContentResponse>



data class ContentResponse(
     @SerializedName("content")
     val loginResponse: LoginResponse
)

也许这可以帮助您。您在内容节点中获取数据,所以

@FormUrlEncoded
@POST("user/login")
suspend fun login(
    @Field("email") email:String,
    @Field("password") password:String,
): Response<ContentResponse>



data class ContentResponse(
     @SerializedName("content")
     val loginResponse: LoginResponse
)

Maybe this can help you. you are getting data in content node so

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文