Complete Guide to Dynamic URL Implementation in Retrofit 2

Nov 28, 2025 · Programming · 10 views · 7.8

Keywords: Retrofit 2 | Dynamic URL | @Url Annotation

Abstract: This article provides an in-depth exploration of two primary methods for implementing dynamic URLs in Retrofit 2: using the @Url annotation and the encoded parameter of the @Path annotation. Through detailed code examples and comparative analysis, it explains the applicable scenarios, implementation steps, and considerations for each method, helping developers choose the most suitable dynamic URL handling solution based on specific requirements.

Background of Dynamic URL Requirements

In modern mobile application development, API endpoint addresses often need to be determined dynamically at runtime. For example, an application might download configuration files from a server containing the latest API addresses, or need to switch base URLs based on different environments selected by users (such as testing or production). Retrofit 2, as a widely used HTTP client library on the Android platform, provides flexible mechanisms to handle such dynamic URL requirements.

Complete Solution with @Url Annotation

Retrofit 2 introduced the @Url annotation, which is the preferred method for handling fully dynamic URLs. This annotation is based on OkHttp's HttpUrl class and can resolve URL addresses like hyperlinks on a web page.

Here is the correct implementation using the @Url annotation:

public interface APIService {
    @GET
    Call<Users> getUsers(@Url String url);
}

In the service implementation, the @Url parameter must be the first parameter of the method. When using this annotation, Retrofit completely ignores the path specified in the @GET annotation and instead uses the complete URL passed in. This means that even if a base URL is set, the actual request will directly use the address provided by the @Url parameter.

When configuring the Retrofit instance, although a base URL still needs to be set, in the case of using the @Url annotation, this base URL is actually completely overridden by the dynamic URL:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

APIService service = retrofit.create(APIService.class);
Call<Users> call = service.getUsers("http://api.mysite.com/user/list");
call.execute();

Encoded Parameter Method with @Path Annotation

For partially dynamic URL scenarios, where certain parts of the base URL remain constant while specific path segments need dynamic replacement, the @Path annotation with the encoded = true parameter can be used.

This method is suitable for scenarios where the URL structure is known but specific path content needs to be determined dynamically:

public interface APIService {
    @GET("{fullUrl}")
    Call<List<Contributor>> contributorsList(@Path(value = "fullUrl", encoded = true) String fullUrl);
}

After setting the encoded = true parameter, Retrofit does not perform URL encoding on the passed path value, thus avoiding the issue of slashes being converted to %2F. However, it is important to note that question mark characters will still be encoded to %3F, so this method is more suitable for handling path segments that do not include query parameters.

Comparative Analysis of the Two Methods

Advantages of @Url Annotation:

Applicable Scenarios for @Path Encoded Method:

Selection Advice: For scenarios requiring fully dynamic URLs, strongly recommend using the @Url annotation; for scenarios requiring only partial path dynamization, consider using the encoded parameter method of @Path.

Key Considerations in Practical Applications

When using dynamic URLs, pay attention to the following key points:

Parameter Position Requirement: When using the @Url annotation, this parameter must be the first parameter of the service method; otherwise, Retrofit cannot parse it correctly.

URL Validation: The passed URL should be a complete and valid HTTP or HTTPS address. Retrofit validates based on OkHttp's URL parsing mechanism, and invalid URLs will cause runtime exceptions.

Encoding Handling: When using the @Path method, although setting encoded = true preserves slash characters, other special characters may still be encoded, requiring appropriate preprocessing based on specific needs.

Performance Considerations: Frequently switching to completely different domains may affect the efficiency of the HTTP connection pool. It is recommended to maintain consistency in the base URL whenever possible.

Conclusion

Retrofit 2 provides an elegant and powerful dynamic URL support mechanism through the @Url annotation, capable of meeting various complex runtime URL configuration requirements. Developers can choose the most suitable method based on specific application scenarios: use the @Url annotation for fully dynamic URLs; consider using the encoded parameter of the @Path annotation for partially dynamic path replacements. Correctly understanding and using these features can significantly improve the flexibility and maintainability of applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.