1.1.18.22.1. fejezet, Retrofit

Basic auth

importálása (build.gradle.kts):

implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")

BaseAuthentication.kt

class BasicAuthInterceptor(username: String, password: String): Interceptor {
    private var credentials: String = Credentials.basic(username, password)
 
    override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
        var request = chain.request()
        request = request.newBuilder().header("Authorization", credentials).build()
        return chain.proceed(request)
    }
}

RestApi.java

public interface RestAPIs
{
    @GET("/user")
    Call<ResponseBody> getHello();
}

NetworkClient.java

package hu.infokristaly.secureapicall;
 
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
 
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
 
public class NetworkClient {
    private Retrofit retrofit;
 
    public Retrofit getRetrofitClient(Context context,String BASE_URL) {
 
        if (retrofit == null) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new BasicAuthInterceptor("admin","admin123"))
                    .build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
 
        }
 
        return retrofit;
    }
 
    void getHelloFromServer(Context context, String ServerAddress) {
        try {
            Retrofit retrofit = getRetrofitClient(context, "http://" + ServerAddress);
 
            RestAPIs restAPIs = retrofit.create(RestAPIs.class);
            //
            Call call = restAPIs.getHello();
 
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call call, Response response) {
                    Log.e("NetworkClient", response.message());
                    try {
                        String result = ((ResponseBody)response.body()).string();
                        Toast.makeText(context, "getHello response ("+response.code()+") " + result, Toast.LENGTH_LONG).show();
                    } catch (IOException|NullPointerException e) {
                        Toast.makeText(context, "getHello response ("+response.code()+") " + e.getLocalizedMessage() , Toast.LENGTH_LONG).show();
                    }
                }
 
                @Override
                public void onFailure(Call call, Throwable t) {
                    Log.e("NetworkClient", t.getLocalizedMessage());
                    Toast.makeText(context, "getHello failed: " + t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                }
            });
        } catch (Exception e) {
            Toast.makeText(context, "getHello failed: " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    }
}