Is there a way to remove a specific header after setting this kind of Interceptor :
public class AuthInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val original: Request = chain.request()
val request: Request = original.newBuilder()
.addHeader(AppConstant.HEADER_APP_TOKEN, AppConfig.apptoken) //<-- need to remove this one for only one request
.addHeader(AppConstant.HEADER_SECURITY_TOKEN, AppConfig.security_token)
.method(original.method(), original.body())
.build()
return chain.proceed(request)
Here is my Retrofit instance :
object RetrofitClientInstance {
private val httpClient = OkHttpClient.Builder()
.addInterceptor(AuthInterceptor())
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
private val retrofit = Retrofit.Builder()
.baseUrl(AppConstant.SERVER_BETA)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build()
fun <T> getRetrofitInstance(service: Class<T>): T {
return retrofit.create(service)
}
}
And this is my API Service :
interface ApiService {
#GET("/app/shoes")
fun getShoes() : Call<Shoes>
}
Thanks for your help :)
Do it the other way around. Add a header to API calls indicating whether to add auth headers or not. Like so:
interface ApiService {
#Headers("isAuthorizable: false")
#GET("/app/Socks")
fun getShoes() : Call<Socks>
#GET("/app/shoes")
fun getShoes() : Call<Shoes>
#GET("/app/sandals")
fun getShoes() : Call<Sandals>
}
Check the header in the Interceptor and add header if condition is satisfied. Like so:
public class AuthInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val original: Request = chain.request()
val shouldAddAuthHeaders = original.headers["isAuthorizable"] != "false"
val requestBuilder = request
.newBuilder()
.method(request.method, request.body)
.removeHeader("isAuthorizable")
if (shouldAddAuthHeaders) {
requestBuilder.addHeader(AppConstant.HEADER_APP_TOKEN, AppConfig.apptoken)
.addHeader(AppConstant.HEADER_SECURITY_TOKEN, AppConfig.security_token)
}
return chain.proceed(requestBuilder.build())
}
}
Note: Using the same logic, one may specify requests for which auth headers are to be added instead of filtering out requests that do not require authentication. That is,
interface ApiService {
#GET("/app/Socks")
fun getShoes() : Call<Socks>
#Headers("isAuthorizable: true")
#GET("/app/shoes")
fun getShoes() : Call<Shoes>
#Headers("isAuthorizable: true")
#GET("/app/sandals")
fun getShoes() : Call<Sandals>
}
public class AuthInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val original: Request = chain.request()
val shouldAddAuthHeaders = original.headers["isAuthorizable"] == "true"
val requestBuilder = request
.newBuilder()
.method(request.method, request.body)
.removeHeader("isAuthorizable")
if (shouldAddAuthHeaders) {
requestBuilder.addHeader(AppConstant.HEADER_APP_TOKEN, AppConfig.apptoken)
.addHeader(AppConstant.HEADER_SECURITY_TOKEN, AppConfig.security_token)
}
return chain.proceed(requestBuilder.build())
}
}
Related
I used retrofit2 to call API. But, when I called it, my app was just shut down. There are not errors in the Logcat. I googled it, but there is not a solution.
And Retrofit2 and converter-gson version is 2.9.0. I set internet permission in AndroidManifest.xml
MainActivity.kt
private fun loadMembers() {
val retrofit = Retrofit.Builder()
.baseUrl(MemberAPI.base_domain)
.addConverterFactory(GsonConverterFactory.create())
.build()
val retrofitService = retrofit.create(MemberInterface::class.java)
retrofitService
.getMember(Constants.api_key)
.enqueue(object: Callback<Member> {
override fun onResponse(call: Call<Member>, response: Response<Member>) {
val members = response.body() as Member
var names = ""
for (member in members.response.body.items.item) {
names += "\n${member.empNm}"
}
binding.text.text = names
}
override fun onFailure(call: Call<Member>, t: Throwable) {
Toast.makeText(baseContext, "실패", Toast.LENGTH_LONG).show()
}
})
}
Interface.kt
interface MemberInterface {
#GET("{api_key}&numOfRows=5&pageNo=1&_type=json")
fun getMember(#Path("api_key") Key: String): Call<Member>
}
Youtube
Video
Try to add an interceptor so you can see all calls logs (headers, body, URLs, etc...). The crash could be related with the parse of the JSON response to the object Member.
Add OkHtpp to your grade dependencies:
implementation "com.squareup.okhttp3:okhttp:5.0.0-alpha.2"
implementation "com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2"
And after that, when you create your Retrofit instance, add the interceptor, should look something like this:
val httpClient = OkHttpClient.Builder()
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
httpClient.addInterceptor(interceptor)
httpClient.addInterceptor(Interceptor { chain: Interceptor.Chain ->
val original: Request = chain.request()
val request: Request = original.newBuilder()
.header("Content-Type", "application/json")
.method(original.method, original.body)
.build()
chain.proceed(request)
})
val okHttpClient = httpClient.build()
val retrofit = Retrofit.Builder()
.baseUrl(MemberAPI.base_domain)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
I have ServiceBuilder object for init retrofit instance
object ServiceBuilder {
//private var url: String? = null
var url = "http://no-google.com" // The default link
fun loadUrl(url: String): ServiceBuilder{
this.url = url
return this
}
private var logger = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
val headerInterceptor = object: Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
request = request.newBuilder()
.addHeader("x-device-type", Build.DEVICE)
.addHeader("Accept-Language", Locale.getDefault().language)
.build()
val response = chain.proceed(request)
return response
}
}
// Create OkHttp Client
private val okHttp = OkHttpClient.Builder()
.callTimeout(5, TimeUnit.SECONDS)
.addInterceptor(headerInterceptor)
.addInterceptor(logger)
// Create Retrofit Builder
private val builder = Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttp.build())
// Create Retrofit Instance
private val retrofit = builder.build()
fun <T> buildService(serviceType: Class<T>): T {
return retrofit.create(serviceType)
}
}
getUrlFromServer() method inside MainActivity
private fun getUrlFromServer(str: String){
val destinationService = ServiceBuilder
.loadUrl("http://google.com") // <-- This call can not reply url into ServiceBuilder object
.buildService(DestinationService::class.java)
val requestCall = destinationService.getList()
requestCall.enqueue(object: Callback<List<Destination>> {
override fun onResponse(
call: Call<List<Destination>>,
response: Response<List<Destination>>
) {
if (response.isSuccessful){
val destinationList = response.body()
//Toast.makeText(this, destinationList.toString(), Toast.LENGTH_LONG)
}
}
override fun onFailure(call: Call<List<Destination>>, t: Throwable) {
TODO("Not yet implemented")
}
})
}
I don't understand why the loadUrl() function which is inside ServiceBuilder can not load url. I need to send url from MainActivity to ServiceBuilder object.
Please tell me how I should decide this issue in good style
Because create retrofit instance, take happen before ServiceBuilder loadUrl function.
Actually retrofit instance, always is created with "http://no-google.com" url!!
fun <T> buildService(serviceType: Class<T>): T {
// Create Retrofit Builder
private val builder = Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttp.build())
// Create Retrofit Instance
private val retrofit = builder.build()
return retrofit.create(serviceType)
}
I want to pass = sign in request params as string. It coverts into %3D upon calling api.
You need to use custom interceptor as below:
class MyInterceptor: Interceptor {
override fun intercept (chain: Interceptor.Chain): Response {
val request = chain.request()
val unEncodedStringUrl = request.url.toString().replace("%3D", "=")
var newRequest = request.newBuilder().url(unEcodedStringUrl).build()
return chain.proceed(newRequest)
}
}
And then use it for OkHttpClient of the retrofit:
fun getOkHttpClient(
myInterceptor: MyInterceptor,
loggingInterceptor: HttpLoggingInterceptor
): OkHttpClient {
return OkHttpClient().newBuilder().addInterceptor(myInterceptor).also {
if (BuildConfig.DEBUG) {
it.addInterceptor(loggingInterceptor)
}
}.build()
}
Finally, use this OkHttpClient for retrofit as below:
fun getRetrofit(moshi: Moshi): Retrofit {
return Retrofit.Builder()
.baseUrl(StaticConstants.baseUrl)
.client(getOkHttpClient())
.addConverterFactory(
MoshiConverterFactory.create(moshi)
)
.build()
}
my application crashes when I have no internet connection : I am looking for a method that handles any exception form the retrofit instance like server is not found exception Timeout No internet connection
RequestRepository : my repository which contain all my functions
class RequestRepository {
/** suspend function to get the result of token request*/
suspend fun getToken(userLoginModel: UserLoginModel): Response<TokenResponse> {
return ApiService.APILogin.getToken(userLoginModel)
}
ApiService : contain my Retofit instance
object ApiService {
private var token: String = ""
fun setToken(tk: String) {
token = tk
}
private val okHttpClient = OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS).addInterceptor { chain ->
val chainRequest = chain.request()
val requestBuilder = chainRequest.newBuilder()
.addHeader("authorization", "Token $token")
.method(chainRequest.method, chainRequest.body)
val request = requestBuilder.build()
chain.proceed(request)
}.build()
var gson = GsonBuilder()
.setLenient()
.create()
private val retrofit by lazy {
Retrofit.Builder()
.baseUrl(LOGIN_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.build()
}
val API: WebServicesApi by lazy {
retrofit.create(WebServicesApi::class.java)
}
WebServicesApi : my interface which contain my requests
interface WebServicesApi {
/** get the token from the API*/
#POST("user/login/")
suspend fun getToken(#Body userLoginModel: UserLoginModel): Response<TokenResponse>
}
LoginViewModel : my viewModel class
class LoginViewModel(private val repository: RequestRepository) : ViewModel() {
var tokenResponse: MutableLiveData<Response<TokenResponse>> = MutableLiveData()
/** using coroutine in getToken function to get the token */
fun getToken(userLoginModel: UserLoginModel) {
viewModelScope.launch(Dispatchers.IO) {
val tResponse = repository.getToken(userLoginModel)
tokenResponse.postValue(tResponse)
Log.d(TAG, "getToken: ${userLoginModel.password}")
}
}
}
You can add a Interceptor for handle error like this:
class GlobalErrorInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
try {
val response = chain.proceed(request)
if (!response.isSuccessful) {
val statusCode = response.code
when (statusCode) {
//Your handle status code in here
}
}
return response
} catch (ex: IOException) {
// You can replace my code with your exception handler code
return Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1)
.message("Can't connect!").code(500).body(
ResponseBody.create(
"application/json; charset=utf-8".toMediaTypeOrNull(),
""
)
).build()
}
}
}
And you must add this class to OkHttpBuider:
val httpBuilder = OkHttpClient.Builder()
......
httpBuilder.addInterceptor(GlobalErrorInterceptor())
I'm trying to add apikey in the URL using custom interceptor but it's not adding the params in the URL so response body is null.
CustomInterceptor
class CustomInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val url = chain.request().url().newBuilder()
.addQueryParameter("apiKey", API_KEY)
.build()
val request = chain.request().newBuilder()
.url(url)
.build()
return chain.proceed(request)
}
}
Client
class Client {
companion object {
const val API_KEY = "123123"
private const val apiUrl = "https://www.omdbapi.com/"
fun <T> create(service: Class<T>): T {
val client = OkHttpClient.Builder()
.addInterceptor(CustomInterceptor())
.build()
return Retrofit.Builder()
.baseUrl(apiUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
.create(service)
}
}
}
IMovie
interface IMovie {
#GET("/")
fun searchMovie(#Query("s") query: String): Call<SearchResult>
}
After sending the request the response body is null and this is the
Actual URL:- https://www.omdbapi.com/?s=Man
Expected URL:- https://www.omdbapi.com/?s=Man&apikey=123123
First create a new httpUrl instance from the existing request adding your query parameter and value:
var request = chain.request()
val httpUrl = request.url().newBuilder().addQueryParameter("token", authToken).build()
Then update the request:
request = request.newBuilder().url(httpUrl).build()
and proceed with it:
return chain.proceed(request)
When you recall the request from the chain (the one you proceed with after manipulation) you are getting the unmodified request again.