在 Android 中,有许多流行的网络库可以用来进行网络请求,每个库都有自己的优点和适用场景。以下是几个常用的库及其简要介绍和示例代码:
OkHttp 是一个高效的 HTTP 客户端,广泛用于 Android 应用中。
gradle展开代码dependencies { implementation 'com.squareup.okhttp3:okhttp:4.9.3' }
java展开代码import okhttp3.*;
public class MainActivity extends AppCompatActivity {
    private final OkHttpClient client = new OkHttpClient();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            checkIn("张三", "123456xx");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void checkIn(String name, String studentID) throws JSONException {
        JSONObject json = new JSONObject();
        json.put("name", name);
        json.put("student_id", studentID);
        RequestBody body = RequestBody.create(json.toString(), MediaType.parse("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url("http://120.46.128.4:8001/check_in")
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    try {
                        JSONObject jsonResponse = new JSONObject(responseBody);
                        final String message = jsonResponse.getString("message");
                        runOnUiThread(() -> Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show());
                    } catch (JSONException e) {
                        e.printStackTrace();
                        runOnUiThread(() -> Toast.makeText(MainActivity.this, "响应解析失败", Toast.LENGTH_SHORT).show());
                    }
                } else {
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "签到失败", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }
}
Retrofit 是一个用于创建网络请求的强大工具,特别适用于 RESTful API。
gradle展开代码dependencies { implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' }
java展开代码import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
    private static final String BASE_URL = "http://120.46.128.4:8001/";
    interface ApiService {
        @POST("check_in")
        Call<ResponseBody> checkIn(@Body RequestBody body);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            checkIn("张三", "123456xx");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void checkIn(String name, String studentID) throws JSONException {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiService apiService = retrofit.create(ApiService.class);
        JSONObject json = new JSONObject();
        json.put("name", name);
        json.put("student_id", studentID);
        RequestBody body = RequestBody.create(json.toString(), MediaType.parse("application/json; charset=utf-8"));
        Call<ResponseBody> call = apiService.checkIn(body);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response.body().string());
                        String message = jsonResponse.getString("message");
                        runOnUiThread(() -> Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show());
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> Toast.makeText(MainActivity.this, "响应解析失败", Toast.LENGTH_SHORT).show());
                    }
                } else {
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "签到失败", Toast.LENGTH_SHORT).show());
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());
            }
        });
    }
}
Volley 是一个由 Google 提供的库,适用于进行较轻量级的网络请求。
gradle展开代码dependencies { implementation 'com.android.volley:volley:1.2.1' }
java展开代码import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    private RequestQueue requestQueue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestQueue = Volley.newRequestQueue(this);
        try {
            checkIn("张三", "123456xx");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void checkIn(String name, String studentID) throws JSONException {
        String url = "http://120.46.128.4:8001/check_in";
        JSONObject json = new JSONObject();
        json.put("name", name);
        json.put("student_id", studentID);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.POST, url, json, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String message = response.getString("message");
                            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, "响应解析失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                    }
                });
        requestQueue.add(jsonObjectRequest);
    }
}
每个库都有其优点:
OkHttp:轻量级、性能好、功能强大,适合做底层 HTTP 客户端。
Retrofit:基于 OkHttp,提供更高级别的 API,支持 RESTful API、可扩展性强,适合复杂的网络请求。
Volley:Google 提供的库,适合处理简单的网络请求、缓存和图像加载。
根据你的需求选择合适的库即可。
你如果需要帮助,请看这里:
csharp展开代码https://docs.qq.com/sheet/DUEdqZ2lmbmR6UVdU?tab=BB08J2


本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!