parent
de4354dd55
commit
051ddf7978
@ -0,0 +1,28 @@
|
||||
package sae.android.sae_2a.VM
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
|
||||
import kotlinx.coroutines.launch
|
||||
import sae.android.sae_2a.data.LoginRepository
|
||||
import sae.android.sae_2a.data.LoginResponse
|
||||
|
||||
class LoginViewModel(
|
||||
private val loginRepository: LoginRepository
|
||||
): ViewModel() {
|
||||
|
||||
fun login( token: String) {
|
||||
viewModelScope.launch {
|
||||
val jsonBody = "{ token: \"$token\"}"
|
||||
val result = try {
|
||||
loginRepository.makeLoginRequest(jsonBody)
|
||||
} catch(e: Exception) {
|
||||
sae.android.sae_2a.data.Result.Error(Exception("Network request failed"))
|
||||
}
|
||||
when (result) {
|
||||
is sae.android.sae_2a.data.Result.Success<LoginResponse> -> print("sucess")
|
||||
else -> ("error")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package sae.android.sae_2a.data
|
||||
|
||||
import android.provider.ContactsContract.CommonDataKinds.Website.URL
|
||||
import org.json.JSONObject
|
||||
import java.io.InputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
class LoginResponseParser {
|
||||
fun parse(inputStream: InputStream): LoginResponse {
|
||||
val responseString = inputStream.bufferedReader().use { it.readText() }
|
||||
// Supposons que la réponse du serveur soit un JSON contenant une clé "token"
|
||||
val jsonObject = JSONObject(responseString)
|
||||
val token = jsonObject.getString("token")
|
||||
return LoginResponse(token)
|
||||
}
|
||||
}
|
||||
|
||||
data class LoginResponse(
|
||||
val token: String
|
||||
)
|
||||
|
||||
sealed class Result<out R> {
|
||||
data class Success<out T>(val data: T) : Result<T>()
|
||||
data class Error(val exception: Exception) : Result<Nothing>()
|
||||
}
|
||||
class LoginRepository(private val responseParser: LoginResponseParser) {
|
||||
|
||||
private val loginUrl = "https://codefirst.iut.uca.fr/containers/antoinejourdain-api_container/Auth/token"
|
||||
|
||||
// Function that makes the network request, blocking the current thread
|
||||
fun makeLoginRequest(
|
||||
jsonBody: String
|
||||
): Result<LoginResponse> {
|
||||
val url = URL(loginUrl)
|
||||
(url.openConnection() as? HttpURLConnection)?.run {
|
||||
requestMethod = "POST"
|
||||
setRequestProperty("Content-Type", "application/json; utf-8")
|
||||
setRequestProperty("Accept", "application/json")
|
||||
doOutput = true
|
||||
outputStream.write(jsonBody.toByteArray())
|
||||
return Result.Success(responseParser.parse(inputStream))
|
||||
}
|
||||
return Result.Error(Exception("Cannot open HttpURLConnection"))
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in new issue