如何根据输入的国家代码列表长度动态生成restcountries API请求URL
动态构造请求URL的实现方案
核心逻辑非常简单:将输入的国家代码列表元素用半角逗号拼接成字符串,再和基础URL组合即可。
通用实现步骤
- 定义固定的基础URL:
https://restcountries.com/v2/alpha?codes= - 对输入的国家代码列表做校验(可选,建议过滤空值、无效字符避免请求出错)
- 使用半角逗号
,作为分隔符,将列表所有元素拼接为单个字符串 - 将基础URL和拼接后的字符串拼接,得到最终请求URL
常用语言代码示例
Python 示例
def build_country_url(code_list: list) -> str: base_url = "https://restcountries.com/v2/alpha?codes=" # 拼接列表,同时过滤空字符串避免出现多余逗号 code_str = ",".join([code.strip() for code in code_list if code.strip()]) return base_url + code_str # 测试用例 print(build_country_url(["kor", "usa", "de"])) # 输出:https://restcountries.com/v2/alpha?codes=kor,usa,de
JavaScript 示例
function buildCountryUrl(codeList) { const baseUrl = "https://restcountries.com/v2/alpha?codes=" // 过滤空值后拼接 const codeStr = codeList.filter(code => code.trim()).join(',') return baseUrl + codeStr } // 测试用例 console.log(buildCountryUrl(["kor", "usa", "de"])) // 输出:https://restcountries.com/v2/alpha?codes=kor,usa,de
Java 示例
import java.util.List; import java.util.stream.Collectors; public class UrlBuilder { private static final String BASE_URL = "https://restcountries.com/v2/alpha?codes="; public static String buildCountryUrl(List<String> codeList) { String codeStr = codeList.stream() .map(String::trim) .filter(code -> !code.isEmpty()) .collect(Collectors.joining(",")); return BASE_URL + codeStr; } public static void main(String[] args) { System.out.println(buildCountryUrl(List.of("kor", "usa", "de"))); // 输出:https://restcountries.com/v2/alpha?codes=kor,usa,de } }
注意事项
- 建议对输入的国家代码做简单合法性校验,比如长度限制在2-3位、只保留字母字符,避免请求返回400错误
- 如果列表为空可以根据业务需求处理,比如抛出异常、或者返回空值避免发起无效请求
内容的提问来源于stack exchange,提问作者lbarros
相关产品推荐
相关产品推荐

