查阅官方文档
访问第三方平台(如高德地图、百度AI、GitHub API)的开发者文档,了解接口功能、请求参数、返回格式及认证方式。
注册并获取凭证
添加网络权限
在 AndroidManifest.xml
中声明网络权限:
<uses-permission android:name="android.permission.INTERNET" />
依赖库选择
示例(Retrofit + Gson):
dependencies { implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0' // 日志调试 }
步骤:
示例代码:
// 定义接口 public interface ApiService { @GET("path/to/resource") Call<ResponseBody> getData(@Query("param") String param); } // 创建 Retrofit 实例 Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") // 替换为实际 Base URL .addConverterFactory(GsonConverterFactory.create()) .build(); // 发起请求 ApiService apiService = retrofit.create(ApiService.class); Call<ResponseBody> call = apiService.getData("value"); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) { // 处理成功逻辑 } else { // 处理错误码(如 404、500) } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { // 处理网络错误(如超时、无网络) } });
OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new LoggingInterceptor()) // 日志拦截器 .build(); Request request = new Request.Builder() .url("https://api.example.com/path?param=value") // 替换为实际 URL .addHeader("Authorization", "Bearer YOUR_TOKEN") // 如需认证 .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 处理失败 } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseBody = response.body().string(); // 解析 JSON/XML } else { // 处理错误码 } } });
数据类型 | 解析工具 | 示例代码 |
---|---|---|
JSON | Gson/Jackson | Gson gson = new Gson();<Br>MyObject obj = gson.fromJson(jsonString, MyObject.class); |
XML | DOM/SAX 或第三方库(如 Simple) | DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();<Br>Document doc = builder.parse(inputStream); |
动态权限申请
Android 6.0+ 需动态申请敏感权限(如定位、存储):
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE); }
HTTPS 配置
若 API 使用自签名证书,需在 res/xml/network_security_config.xml
中配置:
<domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">api.example.com</domain> </domain-config>
并在 AndroidManifest.xml
中引用:
<application ...> <network-security-config srcCompat="@xml/network_security_config" /> </application>
常见错误类型
日志与调试
LoggingInterceptor
打印 HTTP 日志。onFailure
中记录异常详情。解答:
解答:
HttpURLConnection
或 OkHttp 时不受此限制。Access-Control-Allow-Origin