I am not able to receive token form my REST API . I used Interceptors too but unable to access it. Everytime I test run the app , It just shoes me the toast message inside the onFailure() method inside the enqueue method of Retrofit Can anyone please help me out from this. Any help is appreciated !!! Here's the code.
Retrofit:
public static final String BASE_URL = "http://192.168.0.105:8000/";
public static Retrofit retrofit = null;
public static Retrofit getApiClient(){
if(retrofit == null){
//OkHttp Client Instance for using Interceptors
OkHttpClient.Builder okhttpBuilder = new OkHttpClient.Builder();
okhttpBuilder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder newRequest = request.newBuilder().header("Authorization","token");
return chain.proceed(newRequest.build());
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okhttpBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
Login Method inside Activtiy:
private fun login(email:String, password:String) {
val init_login : Login = Login(email,password)
val call:Call<ResponseBody> = apiInterface.login(init_login)
call.enqueue(object :Callback<ResponseBody>{
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
Log.i(LOG_TAG,"Login Failed")
toast("Login Failed")
}
override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
prefConfig.saveToken(response?.body()!!.string())
Log.i(LOG_TAG, "onResponse -> "+response.body().toString())
toast(response?.body()!!.string())
}
})
Retrofit call:
@POST("/login/")
Call<ResponseBody> login(@Body Login login);
Login Parameter used in Call:
public class Login {
@SerializedName("username")
private String user;
@SerializedName("password")
private String password;
public Login(String user,String password){
this.user = user;
this.password = password;
}
}
REST API:
{
"password": [
"This field is required."
],
"username": [
"This field is required."
]
}