首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 中動態構建帶參數的網絡請求 URL 最佳實踐

     編輯:程式設計疑難解答

問題描述

基礎 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();

推薦方案二:OkHttp 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();

推薦方案三:Retrofit 註解方式(最優雅)

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 時,優先使用其構建器或註解方式,確保參數編碼正確、代碼可讀性強、易於測試與維護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved