Android开发:如何用Retrofit发起无参数GET请求并填充Spinner?
没问题!我来给你一步步讲清楚怎么实现——不管你是用Retrofit(现在Android开发的主流选择)还是原生OkHttp,都能轻松搞定这个需求。下面以Android平台为例,详细说明整个流程:
实现步骤
一、准备依赖(以Retrofit为例)
首先在你的build.gradle(Module level)里添加Retrofit和Gson转换器的依赖,这样能自动帮我们解析JSON:
dependencies { // Retrofit核心库 implementation 'com.squareup.retrofit2:retrofit:2.9.0' // Gson转换器,用于自动将JSON转为实体类 implementation 'com.squareup.retrofit2:converter-gson:2.9.0' }
二、定义数据模型类
根据你提供的JSON结构,创建一个Country数据类,用来映射每个国家的信息:
// Kotlin版本 data class Country( val id: String, val sortname: String, val name: String )
// Java版本 public class Country { private String id; private String sortname; private String name; // 必须保留无参构造函数,Gson解析时需要 public Country() {} // Getter和Setter方法 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSortname() { return sortname; } public void setSortname(String sortname) { this.sortname = sortname; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
三、创建Retrofit API接口
定义一个接口,声明无参数的GET请求——因为不需要@Query或其他参数,直接指定接口的端点路径即可:
// Kotlin版本 interface CountryApi { // 替换成你的实际API端点,比如"/api/countries" @GET("countries") fun getCountries(): Call<List<Country>> }
// Java版本 public interface CountryApi { @GET("countries") Call<List<Country>> getCountries(); }
四、发起GET请求并处理响应
在你的Activity或者ViewModel里,初始化Retrofit实例,调用接口方法发起请求,然后处理响应数据:
// Kotlin版本,在Activity中实现 class MainActivity : AppCompatActivity() { private lateinit var countrySpinner: Spinner override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) countrySpinner = findViewById(R.id.country_spinner) // 初始化Retrofit实例 val retrofit = Retrofit.Builder() .baseUrl("https://your-api-base-url.com/") // 替换成你的API基础地址 .addConverterFactory(GsonConverterFactory.create()) .build() val countryApi = retrofit.create(CountryApi::class.java) val call = countryApi.getCountries() // 异步发起请求(避免阻塞主线程) call.enqueue(object : Callback<List<Country>> { override fun onResponse(call: Call<List<Country>>, response: Response<List<Country>>) { if (response.isSuccessful) { val countryList = response.body() countryList?.let { // 数据获取成功,填充到Spinner setupSpinner(it) } } else { // 处理请求失败的情况 Toast.makeText(this@MainActivity, "请求失败,请稍后重试", Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call<List<Country>>, t: Throwable) { // 处理网络错误 Toast.makeText(this@MainActivity, "网络错误:${t.message}", Toast.LENGTH_SHORT).show() } }) } // 将数据适配到Spinner的方法 private fun setupSpinner(countryList: List<Country>) { // 创建适配器,用国家名称作为Spinner的显示内容 val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, countryList.map { it.name }) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) countrySpinner.adapter = adapter } }
五、备选方案:用OkHttp发起请求
如果你不想用Retrofit,也可以用原生OkHttp来实现:
// Kotlin版本 val client = OkHttpClient() val request = Request.Builder() .url("https://your-api-base-url.com/countries") // 完整的API地址 .build() // 默认就是GET请求,无需额外指定 client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { // 处理网络错误,注意要切回主线程更新UI runOnUiThread { Toast.makeText(this@MainActivity, "网络错误:${e.message}", Toast.LENGTH_SHORT).show() } } override fun onResponse(call: Call, response: Response) { response.body()?.let { responseBody -> val jsonString = responseBody.string() // 用Gson手动解析JSON数组 val gson = Gson() val countryList = gson.fromJson(jsonString, object : TypeToken<List<Country>>() {}.type) // 切回主线程更新Spinner runOnUiThread { setupSpinner(countryList) } } } })
内容的提问来源于stack exchange,提问作者Subham Kaps
相关产品推荐
相关产品推荐

