上一篇
安卓做网络请求的代码
- 行业动态
- 2025-04-24
- 5
“
java,// 使用OkHttp实现简单GET请求,public void sendRequest() {, OkHttpClient client = new OkHttpClient();, Request request = new Request.Builder().url("https://api.example.com").build();, client.newCall(request).enqueue(new Callback() {, @Override public void onFailure(Call call, Exception e) {}, @Override public void onResponse(Call call, Response response) throws IOException {, String res = response.body().string(); // 处理响应数据, }, });,},
` ,需在AndroidManifest声明
`
安卓网络请求实现方式
常用网络请求库对比
库名 | 特点 | 适用场景 |
---|---|---|
OkHttp | 轻量级、支持同步/异步请求、自动处理连接池 | 简单REST API调用 |
Retrofit | 基于OkHttp、支持注解式接口、强类型转换、支持RxJava/协程 | 复杂API接口集成 |
HttpURLConnection | Android原生API、无需额外依赖 | 基础网络功能实现 |
Volley | Google出品、支持图片加载、缓存机制、适合小数据量请求 | 列表数据加载 |
OkHttp基础用法示例
// 1. 添加依赖(build.gradle) // implementation 'com.squareup.okhttp3:okhttp:4.11.0' // 2. GET请求示例 public void sendGetRequest() { OkHttpClient client = new OkHttpClient(); String url = "https://api.example.com/data"; Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 处理失败(如网络错误) Log.e("NetworkError", e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { // 处理成功响应 String result = response.body().string(); // 更新UI需切换到主线程 runOnUiThread(() -> textView.setText(result)); } else { // 处理非200响应码 Log.e("HTTPError", "Code: " + response.code()); } } }); }
Retrofit进阶用法示例
// 1. 添加依赖(build.gradle) // implementation 'com.squareup.retrofit2:retrofit:2.9.0' // implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // 2. 定义API接口 public interface ApiService { @GET("users/{id}") Call<User> getUser(@Path("id") int userId); @POST("login") Call<Token> login(@Field("username") String username, @Field("password") String password); } // 3. 创建Retrofit实例 Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") // 必须以/ .addConverterFactory(GsonConverterFactory.create()) .build(); // 4. 发起请求 ApiService apiService = retrofit.create(ApiService.class); Call<User> call = apiService.getUser(123); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { if (response.isSuccessful()) { User user = response.body(); // 处理用户数据 } else { // 处理错误响应(如404) } } @Override public void onFailure(Call<User> call, Throwable t) { // 处理网络错误 } });
关键注意事项
权限配置:需在
AndroidManifest.xml
声明网络权限<uses-permission android:name="android.permission.INTERNET" />
主线程限制:Android禁止在主线程执行网络操作,解决方案:
- 使用子线程(
new Thread
) - 异步任务(
AsyncTask
)已过时 - Kotlin协程(推荐)
- RxJava/RxAndroid
- 使用子线程(
HTTPS安全:自Android 9起,明文HTTP流量被禁止,需配置:
<application android:usesCleartextTraffic="true" />
常见问题与解决方案
Q1:如何处理SSL证书验证?
A1:可通过自定义TrustManager
跳过验证(仅限测试环境):
OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(new NoSSLFactory(), new TrustAllCerts()) .build();
注:生产环境必须使用合法证书
Q2:遇到404/500等HTTP错误码如何处理?
A2:需根据response.code()
进行分类处理:
- 4xx:客户端错误(如参数错误)
- 5xx:服务器错误(可重试)
- 其他错误码:按业务需求处理
建议统一封装错误处理逻辑,if (!response.isSuccessful()) { handleHttpError(response.code()); }