在 Android 中,有许多流行的网络库可以用来进行网络请求,每个库都有自己的优点和适用场景。以下是几个常用的库及其简要介绍和示例代码:
1. OkHttp
OkHttp 是一个高效的 HTTP 客户端,广泛用于 Android 应用中。
添加依赖
dependencies {implementation 'com.squareup.okhttp3:okhttp:4.9.3'
}
使用示例
import okhttp3.*;public class MainActivity extends AppCompatActivity {private final OkHttpClient client = new OkHttpClient();@Overrideprotected 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() {@Overridepublic void onFailure(Call call, IOException e) {runOnUiThread(() -> Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());}@Overridepublic 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());}}});}
}
2. Retrofit
Retrofit 是一个用于创建网络请求的强大工具,特别适用于 RESTful API。
添加依赖
dependencies {implementation 'com.squareup.retrofit2:retrofit:2.9.0'implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
使用示例
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);}@Overrideprotected 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>() {@Overridepublic 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());}}@Overridepublic void onFailure(Call<ResponseBody> call, Throwable t) {runOnUiThread(() -> Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());}});}
}
3. Volley
Volley 是一个由 Google 提供的库,适用于进行较轻量级的网络请求。
添加依赖
dependencies {implementation 'com.android.volley:volley:1.2.1'
}
使用示例
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;@Overrideprotected 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>() {@Overridepublic 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() {@Overridepublic void onErrorResponse(VolleyError error) {Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();}});requestQueue.add(jsonObjectRequest);}
}
每个库都有其优点:
- OkHttp:轻量级、性能好、功能强大,适合做底层 HTTP 客户端。
- Retrofit:基于 OkHttp,提供更高级别的 API,支持 RESTful API、可扩展性强,适合复杂的网络请求。
- Volley:Google 提供的库,适合处理简单的网络请求、缓存和图像加载。
根据你的需求选择合适的库即可。