Retrofit2 is removing characters after hostname from the base URL? And How to fix it.

You must have experienced the trauma of searching for that simple, stupid, annoying bug that’s not letting you give your code for testing or allowing you to sleep peacefully. The semicolon jokes are too popular in the programming community. But I don’t think it’s relevant anymore because the IDEs these days are super intelligent to tell you there is something wrong in your code even before you compile it. But today, I faced one of those cute little bugs that are way too small to find out. Nope. Not a semicolon. I accidentally added a leading /. And it took me around 5 hours to realize this was the issue.

I was checking an issue reported by our testing team that they are not able to search for the district details, and the app is crashing. But everything else is working fine. Hmm… something is fishy. So I dig into our codebase and especially the Retrofit related classes. Found there is something wrong with API calls. Let’s see what I found.

My Base URL

My code for the interface. Note the difference in the two end URLs

End URL for getting the details of the districts

End URL for getting the details of the states

Can you identify the difference in a single glance? Imagine you are looking at a file that has tons of end URLs written in it. It’s like you are looking for a needle in a haystack. When you are running the code, searchByState is working correctly, but searchByDistrict is giving you an error URL not found. If an issue like this occurs, the first thing that comes to your mind is to blame it on the backend developer :p. Well, I did the same. But he was patient enough to tell me that there is a difference in the two API calls.

API call for getting the district details

API call for getting the state details

It missed the character after the hostname. i.e., ‘service’ in this case. The reason? Like I said earlier, we accidentally added a leading /.

When I read about it, it says that Retrofit 2 uses the same rules that an <a href=""> would. So, when we added a leading /to our end URL, it accidentally told Retrofit that it is an absolute path on the host. By removing the leading /, the URL then becomes relative and will combine with the path segments which are part of the base URL.

It is one of those fascinating bugs I have resolved recently. I hope it will help others to resolve it quickly and not waste their precious developer hours. Please share it with your developer friends if possible, and do give a clap if you find it helpful.

Thank you.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store