If your URL has query parameters, this solution will not work, as it will add '/' to the end of your base URL. for example if your url is
https://www.google.com/?q=test
then the above solution will try to send a request to
https://www.google.com/?q=test/
which will fail due to the format of the mall.
What we can do is take one extra step and parse the URL. By parsing, I mean just delete all URL parameters and send them to QueryMap .
Here's how:
We should have the structure described above with a slight change in our interface
public interface General { @GET("/") void getSomething(@QueryMap Map<String,String> queryMap, Callback<SomeObject> callback); }
I just added QueryMap to the above interface, and now we can use this parser method:
public static void getSomething(@NonNull String urlString, @NonNull Callback<SomeObject> callback){ Uri uri = Uri.parse(urlString); Set<String> queryParameterNames = uri.getQueryParameterNames(); String host = uri.getHost(); HashMap<String,String> queryMap = new HashMap<>(); Iterator<String> iterator = queryParameterNames.iterator(); while(iterator.hasNext()){ String queryName = iterator.next(); String queryParameter = uri.getQueryParameter(queryName); queryMap.put(queryName, queryParameter); } getHostAdapter(host) .create(General.class) .getSomething(queryMap, callback); }
Now you can call this method as follows:
getSomething("https://www.google.com/?q=test");
Enjoy the coding.
Note: QueryMap added in Retrofit v1.4.0
source share