OKHttp是一个开源的HTTP客户端库,用于在Android中发送和接收网络请求。下面是一个示例,展示了如何在Android中使用OKHttp发送GET和POST请求。
首先,确保在项目的build.gradle文件中添加以下依赖项:
dependencies {implementation 'com.squareup.okhttp3:okhttp:4.9.1'}发送GET请求的示例代码如下:
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() {@Overridepublic void onFailure(Call call, IOException e) {// 处理请求失败的情况}@Overridepublic void onResponse(Call call, Response response) throws IOException {// 处理请求成功的情况String responseData = response.body().string();// 在这里处理服务器返回的数据}});发送POST请求的示例代码如下:
OkHttpClient client = new OkHttpClient();String url = "https://api.example.com/data";String json = "{\"key\":\"value\"}"; // POST请求的参数,这里使用JSON格式RequestBody requestBody = RequestBody.create(json, MediaType.parse("application/json"));Request request = new Request.Builder().url(url).post(requestBody).build();client.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {// 处理请求失败的情况}@Overridepublic void onResponse(Call call, Response response) throws IOException {// 处理请求成功的情况String responseData = response.body().string();// 在这里处理服务器返回的数据}});这只是OKHttp的基本用法,你还可以使用它来添加请求头、设置超时时间、处理文件上传等更复杂的操作。详细的使用方法可以参考OKHttp的官方文档。

