title: How to add querey parameter only if there's a value in second request in Retrofit or OkHttpClient interceptor
body: <p>In this app, I used <a href="https://developers.google.com/blogger/docs/3.0/getting_started" rel="nofollow noreferrer">Blogger API</a>, I have this method that gets posts</p>
  <pre><code>@GET
  suspend fun getPostList(@Url URL: String): Response&lt;PostList&gt;
  </code></pre>
  <p>this is the base URL that I used with it</p>
  <pre><code>const val BASE_URL = &quot;https://www.googleapis.com/blogger/v3/blogs/$BLOG_ID/posts/&quot;
  </code></pre>
  <p>when at first request it become like this</p>
  <pre><code>https://www.googleapis.com/blogger/v3/blogs/12345678910/posts/maxResults=20&amp;key=API_KEY
  </code></pre>
  <p>when the second request it should be getting a token parameter <code>pageToken=ABCDE</code> in result that I needed to do pagination, so I edit the <strong>BASE URL</strong> in viewModel and add the <code>pageToken</code> parameter to it then I pass it to the getPostList method again</p>
  <p>and it looks like this</p>
  <pre><code>https://www.googleapis.com/blogger/v3/blogs/12345678910/posts/maxResults=20&amp;pageToken=ABCDEFG&amp;key=API_KEY
  </code></pre>
  <p>this my network layer</p>
  <pre><code>  private val interceptor : HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
          this.level = HttpLoggingInterceptor.Level.BODY
      }
  
      @Singleton
      @Provides
      fun postAPIService(): PostAPIService {
          return Retrofit.Builder()
              .baseUrl(Constants.BASE_URL)
              .client(
                  OkHttpClient.Builder().readTimeout(
                      15, TimeUnit.SECONDS
                  ).connectTimeout(15, TimeUnit.SECONDS)
                      .addNetworkInterceptor(interceptor)
                      .addInterceptor { chain -&gt;
                          val url = chain
                              .request()
                              .url
                              .newBuilder()
                              .addQueryParameter(&quot;maxResults&quot;, Constants.MAX_RESULT)
                              .addQueryParameter(&quot;key&quot;, Constants.API_KEY)
                              .build()
                          chain.proceed(chain.request().newBuilder().url(url)
                              .build())
                      }.build()
  
              )
              .addConverterFactory(GsonConverterFactory.create())
              .build().create(PostAPIService::class.java)
      }
  }
  </code></pre>
  <p>In ViewModel layer</p>
  <pre><code>    /** RETROFIT **/
      var postsResponse: MutableLiveData&lt;NetworkResult&lt;PostList&gt;&gt; = MutableLiveData()
      var postListResponse: PostList? = null
  
      val label = MutableLiveData&lt;String&gt;()
      var finalURL: MutableLiveData&lt;String&gt; = MutableLiveData()
      private val token = MutableLiveData&lt;String?&gt;()
  
  private suspend fun getPostsSafeCall() {
  
          postsResponse.postValue(NetworkResult.Loading())
  
          Log.e(TAG, &quot;getPostsSafeCall finalURL is ${finalURL.value!!}&quot;)
  
          if (hasInternetConnection()) {
              try {
  
                  if (finalURL.value.isNullOrEmpty()) {
                      finalURL.postValue(BASE_URL)
                  }
  
                  val response = mainRepository.remoteDataSource.getPostList(finalURL.value!!)
                  postsResponse.value = handlePostsResponse(response)
  
              } catch (exception: Exception) {
                  postsResponse.postValue(NetworkResult.Error(exception.message.toString()))
  //                Log.e(TAG, e.message + e.cause)
                  if (exception is HttpException) {
                      errorCode.postValue(exception.code())
                      Log.e(TAG, &quot;getPostsSafeCall: errorCode $errorCode&quot;)
                      Log.e(TAG, &quot;getPostsSafeCall: ${exception.message.toString()}&quot;)
                  }
              }
          } else {
              postsResponse.postValue(NetworkResult.Error(&quot;No Internet Connection.&quot;))
          }
      }
  
  
  private fun handlePostsResponse(response: Response&lt;PostList&gt;): NetworkResult&lt;PostList&gt; {
          if (response.isSuccessful) {
  
              token.value = response.body()?.nextPageToken
  
              Log.d(TAG, &quot;handlePostsResponse: token = ${response.body()?.nextPageToken.toString()}&quot;)
  
              response.body()?.let { resultResponse -&gt;
                  Log.d(
                      TAG, &quot;handlePostsResponse: old token is: ${token.value} &quot; +
                              &quot;new token is: ${resultResponse.nextPageToken}&quot;
                  )
  
                  finalURL.postValue(
                      BASE_URL + &quot;&amp;pageToken=${token.value}&quot;
                  )
  
                  if (postListResponse == null) {
                      postListResponse = resultResponse
                  } else {
                      val oldPosts = postListResponse?.items
                      val newPosts = resultResponse.items
                      oldPosts?.addAll(newPosts)
                  }
  
                  Log.d(TAG, &quot;handlePostsResponse: ${token.value}&quot;)
                  Log.e(TAG, &quot;handlePostsResponse finalURL is ${finalURL.value!!}&quot;)
  
                  for (item in resultResponse.items) {
                      insertItem(item)
                  }
                  return NetworkResult.Success(postListResponse ?: resultResponse)
  
              }
  
          } else  {
              if (token.value == null) {
                  errorCode.postValue(400)
              } else {
                  errorCode.postValue(response.code())
              }
  
              Log.d(TAG, &quot;handlePostsResponse: ${response.code().toString()}&quot;)
              Log.d(TAG, &quot;handlePostsResponse: ${response.headers().toString()}&quot;)
              Log.d(TAG, &quot;handlePostsResponse: ${response.headers().toString()}&quot;)
  //        Log.d(TAG, &quot;handlePostsResponse: final ${finalURL.value.toString()}&quot;)
              return NetworkResult.Error(
                  &quot;network results of handlePostsResponse ${response.body().toString()}&quot;
              )
          }
          return NetworkResult.Error(
              &quot;network results of handlePostsResponse ${response.body().toString()}&quot;
          )
      }
  </code></pre>
  <h2>WHAT I NEED</h2>
  <p>a way to inject <code>pageToken</code> parameter <strong>dynamically</strong> only when there's a value (NOT NULL OR EMPTY) to avoid the following in final/base URL</p>
  <pre><code>https://www.googleapis.com/blogger/v3/blogs/4294497614198718393/posts/?maxResults=20&amp;pageToken=null&amp;key=API_KEY
  </code></pre>
  <p>this cause error 400 badRequest</p>
  <pre><code>{
    &quot;error&quot;: {
      &quot;code&quot;: 400,
      &quot;message&quot;: &quot;We're sorry, but the value for field pageToken was not valid.&quot;,
      &quot;errors&quot;: [
        {
          &quot;message&quot;: &quot;We're sorry, but the value for field pageToken was not valid.&quot;,
          &quot;domain&quot;: &quot;global&quot;,
          &quot;reason&quot;: &quot;invalid&quot;
        }
      ]
    }
  }
  </code></pre>
  <p>I tried edit the PostAPIService method to look like that</p>
  <pre><code>  @GET(&quot;posts&quot;)
      suspend fun getPostList(@Query(&quot;pageToken&quot;) pageToken: String=&quot;&quot;): Response&lt;PostList&gt;
  </code></pre>
  <p>and use it in viewModel like this</p>
  <pre><code> val response = if (token.value.isNullOrEmpty()) {
   mainRepository.remoteDataSource.getPostList()
   } else {
  mainRepository.remoteDataSource.getPostList(token.value!!)
  }
  </code></pre>
  <p>but unfortunately this causes badRequest also because of <code>pageToken=null</code> in <strong>BASE_URL</strong></p>