I already search all around the places on internet how to add basic auth using retrofit2 but still no luck. I already implemented a simple login mechanism but basic auth must be use in order for successful login.
My model
public class ResObj {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
ApiUtils.java
public class ApiUtils {
public static final String BASE_URL = "xxxxx";
public static UserService getUserService(){
return RetrofitClient.getClient(BASE_URL).create(UserService.class);
}
}
RetrofitClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url){
if(retrofit == null){
retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
UserService.java
public interface UserService {
@GET("login?username={username}&password={password}")
Call<ResObj> login(@Path("username") String username, @Path("password") String password);
}
LoginActivity.java
private void doLogin(String username, String password){
Call<ResObj> call = userService.login(username, password);
call.enqueue(new Callback<ResObj>() {
@Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
if(response.isSuccessful()){
ResObj resObj = response.body();
if(resObj.getMessage().equals("true")){
Intent intent = new Intent(TextLoginActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(TextLoginActivity.this, "The username and password is incorrect", Toast.LENGTH_SHORT).show();
}
} else{
Toast.makeText(TextLoginActivity.this, "Error! Please try again!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ResObj> call, Throwable t) {
Toast.makeText(TextLoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}