基礎 URL:https://www.example.com/api/get_post?post_type=news&id=,需在 id= 後動態拼接變量值。
String id = "123";
String url = "https://www.example.com/api/get_post?post_type=news&id=" + id;
// 缺點:需手動處理 URL 編碼,參數含特殊字符時易出錯
Uri.Builder(Android 官方 API)String baseUrl = "https://www.example.com/api/get_post";
Uri uri = Uri.parse(baseUrl)
.buildUpon()
.appendQueryParameter("post_type", "news")
.appendQueryParameter("id", id) // 自動處理編碼
.build();
String finalUrl = uri.toString();
HttpUrl.Builder(若使用 OkHttp)HttpUrl url = new HttpUrl.Builder()
.scheme("http")
.host("www.example.com")
.addPathSegments("api/get_post")
.addQueryParameter("post_type", "news")
.addQueryParameter("id", id)
.build();
public interface ApiService {
@GET("api/get_post")
Call<ResponseBody> getPost(@Query("post_type") String type, @Query("id") String id);
}
// 使用
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.example.com/").build();
ApiService service = retrofit.create(ApiService.class);
service.getPost("news", id).enqueue(...);
| 方式 | 自動編碼 | 類型安全 | 可維護性 |
|---|---|---|---|
| 字符串拼接 | ❌ | ❌ | 低 |
| Uri.Builder | ✅ | ❌ | 中 |
| OkHttp HttpUrl | ✅ | ❌ | 中高 |
| Retrofit | ✅ | ✅ | 高 |
簡單場景用 Uri.Builder;網絡層已引入 OkHttp/Retrofit 時,優先使用其構建器或註解方式,確保參數編碼正確、代碼可讀性強、易於測試與維護。