在 Java Spring Boot 项目中可以很方便地集成OkHttp
来发送GET
和POST
请求。以下是具体步骤:
一、添加依赖
在项目的pom.xml
文件中添加OkHttp
的依赖:
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.11.0</version>
</dependency>
二、发送 GET 请求
- 创建一个工具类来封装
OkHttp
的请求方法:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;import java.io.IOException;public class OkHttpUtil {public static String sendGetRequest(String url) throws IOException {OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url(url).build();try (Response response = client.newCall(request).execute()) {if (!response.isSuccessful()) {throw new IOException("Unexpected code " + response);}return response.body().string();}}
}
- 在需要发送
GET
请求的地方调用这个方法:
import java.io.IOException;public class Main {public static void main(String[] args) {try {String response = OkHttpUtil.sendGetRequest("https://api.example.com/data");System.out.println(response);} catch (IOException e) {e.printStackTrace();}}
}
三、发送 POST 请求
- 在工具类中添加发送
POST
请求的方法:
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;import java.io.IOException;public class OkHttpUtil {//... 前面的 sendGetRequest 方法public static String sendPostRequest(String url, String jsonData) throws IOException {OkHttpClient client = new OkHttpClient();MediaType mediaType = MediaType.parse("application/json; charset=utf-8");RequestBody body = RequestBody.create(jsonData, mediaType);Request request = new Request.Builder().url(url).post(body).build();try (Response response = client.newCall(request).execute()) {if (!response.isSuccessful()) {throw new IOException("Unexpected code " + response);}return response.body().string();}}
}
- 在需要发送
POST
请求的地方调用这个方法:
import java.io.IOException;public class Main {public static void main(String[] args) {try {String jsonData = "{\"key\":\"value\"}";String response = OkHttpUtil.sendPostRequest("https://api.example.com/post-endpoint", jsonData);System.out.println(response);} catch (IOException e) {e.printStackTrace();}}
}
在上述代码中,sendGetRequest
方法用于发送GET
请求,sendPostRequest
方法用于发送POST
请求并传入要发送的 JSON 数据。请确保在实际使用中处理可能出现的异常情况,并根据实际需求调整请求的 URL 和数据。