SpringBoot okhtt tool class encapsulation
Using OkHttp in Spring Boot projects makes it easy to make HTTP requests.
Add OkHttp's dependencies to the file:
<dependencies> <!-- OkHttp --> <dependency> <groupId>.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.3</version> </dependency> </dependencies>
The following is an example of an OkHttp tool class that encapsulates common HTTP request methods (GET, POST)
import okhttp3.*; import ; import ; import ; /** * OkHttp tool class, encapsulate common HTTP request methods */ public class OkHttpUtils { private static final OkHttpClient client; static { // Initialize OkHttpClient client = new () .connectTimeout(10, ) // Connection timeout .readTimeout(30, ) // Read timeout .writeTimeout(30, ) // Write timeout time .build(); } /** * Send a GET request * * @param url Requested URL * @return Response result string * @throws IOException Network request exception */ public static String sendGetRequest(String url) throws IOException { Request request = new () .url(url) .build(); try (Response response = (request).execute()) { if (() && () != null) { return ().string(); } return null; } } /** * Send a GET request with parameters * * @param url Requested URL * @param params Request parameters * @return Response result string * @throws IOException Network request exception */ public static String sendGetRequest(String url, Map<String, String> params) throws IOException { urlBuilder = (url).newBuilder(); if (params != null) { for (<String, String> entry : ()) { ((), ()); } } String finalUrl = ().toString(); return sendGetRequest(finalUrl); } /** * Send a POST request, the request body is in JSON format * * @param url Requested URL * @param jsonBody JSON format request body * @return Response result string * @throws IOException Network request exception */ public static String sendPostRequest(String url, String jsonBody) throws IOException { MediaType JSON = ("application/json; charset=utf-8"); RequestBody body = (jsonBody, JSON); Request request = new () .url(url) .post(body) .build(); try (Response response = (request).execute()) { if (() && () != null) { return ().string(); } return null; } } /** * Send a POST request, the request body is in form format * * @param url Requested URL * @param params form parameters * @return Response result string * @throws IOException Network request exception */ public static String sendPostFormRequest(String url, Map<String, String> params) throws IOException { formBodyBuilder = new (); if (params != null) { for (<String, String> entry : ()) { ((), ()); } } RequestBody formBody = (); Request request = new () .url(url) .post(formBody) .build(); try (Response response = (request).execute()) { if (() && () != null) { return ().string(); } return null; } } }
Example of usage
Here is how to use this tool class in Spring Boot Controller:
import ; import ; import ; import ; import ; import ; @RestController @RequestMapping("/http") public class HttpController { @GetMapping("/get") public String getRequest() throws IOException { String url = "/todos/1"; return (url); } @GetMapping("/getWithParams") public String getRequestWithParams() throws IOException { String url = "/posts"; Map<String, String> params = new HashMap<>(); ("userId", "1"); return (url, params); } @GetMapping("/postJson") public String postJsonRequest() throws IOException { String url = "/posts"; String jsonBody = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"; return (url, jsonBody); } @GetMapping("/postForm") public String postFormRequest() throws IOException { String url = "/posts"; Map<String, String> params = new HashMap<>(); ("title", "foo"); ("body", "bar"); ("userId", "1"); return (url, params); } }
Things to note
- In this tool class
OkHttpClient
Is statically initialized, sharing an instance throughout the application to improve performance and reuse connections. - For exception handling, the current example simply
IOException
Throw, in actual application, you may need to perform more detailed exception handling according to the specific situation, such as recording logs, returning appropriate error information, etc. - Make sure that possible network exceptions and timeouts are handled during use to ensure the robustness of the application.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.