2

I have a String url with queries (https://example.com/path/segments?q1=1&q2=2 for example). I need to add trailing slash (https://example.com/path/segments/?q1=1&q2=2) before queries if it does not exist using okhttp 3. How can I do this?

Alexey Nikitin
  • 604
  • 7
  • 22

2 Answers2

3

Before using the string you could just do an replace on the ? and replace it with /? and you get the result you want.

Here's an example in Kotlin

var url:String = "https://example.com/path/segments?q1=1&q2=2"
url = url.replace("?", "/?")

This should work since the query variables should be urlencoded and there should only be one occurence of ? in your urls.

nilsolofsson
  • 96
  • 2
  • 6
  • It will work, but I thought there is something better with [HttpUrl.Builder](https://square.github.io/okhttp/4.x/okhttp/okhttp3/-http-url/-builder/) using – Alexey Nikitin Oct 28 '19 at 06:44
3

Use httpUrlBuilder.addPathSegment("") to force a trailing slash at the end of the path. HttpUrl models each path segment as being prefixed by a /, with an empty string indicating a lone slash.

Alexey Nikitin
  • 604
  • 7
  • 22
Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128