Вот пример код, написанный на Javascript:
Код: Выделить всё
const axios = require('axios');
const creds = {
grant_type: "password",
username: '',
password: '',
client_id: '',
client_secret: ''
};
const resp = await axios({
method: 'POST',
url: `https://example.com`,
data: creds
});
const { access_token, refresh_token } = resp.data;
console.log(access_token, refresh_token);
API-сервис:
Код: Выделить всё
@Headers(
value = [
"Content-Type: application/x-www-form-urlencoded"
]
)
@POST("data")
suspend fun getAuthenticating(@Body authData: AuthData): Response
Код: Выделить всё
val interceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
val client = OkHttpClient.Builder().apply {
addInterceptor(interceptor)
}.build()
private val AUTH_URL = BuildConfig.AUTH_URL
@Singleton
@Provides
fun provideAuthRetrofit(): Retrofit {
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(AUTH_URL)
.client(client)
.build()
}
Код: Выделить всё
data class AuthData(
@SerializedName("grant_type")
val grantType: String = "password",
@SerializedName("username")
val username: String = "",
@SerializedName("password")
val password: String = "",
@SerializedName("client_id")
val clientId: String = "",
@SerializedName("client_secret")
val clientSecret: String = ""
)
Код: Выделить всё
--> POST https://example.com/data
Content-Type: application/x-www-form-urlencoded
Content-Length: 186
{"client_id":"sample","client_secret":"sample","grant_type":"password","password":"abc","username":"abc"}
--> END POST (186-byte body)
Подробнее здесь: [url]https://stackoverflow.com/questions/78256057/how-to-do-the-correct-post-request-with-retrofit-kotlin[/url]
Мобильная версия