HTTP API调用是Android应用与服务器交互的核心方式,通过HTTP协议(如GET/POST/PUT/DELETE)请求远程接口获取或提交数据。关键组件包括:
https://api.example.com/data
)Authorization
)、内容类型(如Content-Type: application/json
)// GET请求示例
URL url = new URL("https://api.example.com/data");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer token");
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("API_RESPONSE", response.toString());
}
conn.disconnect();
优势:简化代码、支持异步、自动JSON解析。
// 1. 定义API接口
interface ApiService {
@GET("data")
suspend fun getData(@Header("Authorization") token: String): Response<DataModel>
}
// 2. 创建Retrofit实例
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(OkHttpClient.Builder().build())
.build()
// 3. 发起请求(CoroutineScope中)
val api = retrofit.create(ApiService::class.java)
try {
val response = api.getData("Bearer token")
if (response.isSuccessful) {
val data = response.body()
}
} catch (e: Exception) {
e.printStackTrace()
}
Permission denied
。AndroidManifest.xml
添加:AndroidManifest.xml
添加:NetworkOnMainThreadException
。Coroutine
、RxJava
)或AsyncTask
(已废弃)。SSLHandshakeException
。JsonSyntaxException
或字段映射错误。DataModel
)字段与JSON键名一致。@SerializedName
注解处理不一致字段:@SerializedName
注解处理不一致字段:Authorization
头。Authorization
头。Cache-Control
头或OkHttp缓存减少重复请求。通过合理选择工具和遵循最佳实践,可高效实现稳定可靠的API调用。