Step 1 :Create interface named ApiInterface.kt.
interface ApiInterface {
@POST("token")
fun getToken(): Call<ResponseBody>
}
Step 2 : In your activity paste these functions
public static Retrofit getClient(final String token) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addInterceptor(new NetInterceptor())
.addInterceptor(chain -> {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Basic " + getBasicAuth(clientId, clientServer))
.build();
return chain.proceed(newRequest);
})
//.followRedirects(false)
//.followSslRedirects(false)
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build();
return new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
convert basic auth to base64
private fun getBasicAuth(client_id: String, client_secret: String): String {
val data = ("$client_id:$client_secret").toByteArray(StandardCharsets.UTF_8)
return Base64.encodeToString(data, Base64.DEFAULT)
}
Step : 3 Do an api call
private fun apiCall() {
val call = getClient()!!.create(ApiInterface::class.java).getToken()
call.enqueue(object : Callback<UserResponse> {
override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
Toast.makeText(this@MainActivity, response.code().toString()
+ " " + response.body().toString(), Toast.LENGTH_SHORT).show()
}
override fun onFailure(call: Call<UserResponse>, t: Throwable) {
Toast.makeText(this@MainActivity, t.localizedMessage!!.toString(),
Toast.LENGTH_SHORT).show()
}
})
}
Step 4 : call api in your onCreate() method.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
apiCall()
}