Java工具类--OkHttp工具类

以springboot项目举例

1.pom添加maven依赖

复制代码
<dependency>  
    <groupId>com.squareup.okhttp3</groupId>  
    <artifactId>okhttp</artifactId>  
    <version>你的OkHttp版本</version>  
</dependency>

2.创建OkHttp工具类:

接下来,创建一个Java类来封装OkHttp的使用。这个类可以是一个Spring组件(例如,使用@Component注解),但通常它只是一个普通的Java类就足够了,因为它不依赖于Spring容器中的其他bean。

java 复制代码
import okhttp3.OkHttpClient;  
import okhttp3.Request;  
import okhttp3.Response;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  

import java.io.IOException;  
import java.util.concurrent.TimeUnit;  

public class OkHttpUtil {  

    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);  
    private static final OkHttpClient client = new OkHttpClient.Builder()  
            .connectTimeout(30, TimeUnit.SECONDS)  
            .readTimeout(30, TimeUnit.SECONDS)  
            .writeTimeout(30, TimeUnit.SECONDS)  
            .build();  

    private OkHttpUtil() {  
        // 私有构造函数,防止实例化  
    }  

    //有些小伙伴奇怪为什么没有带参的get请求,因为基础get都不支持
    //正常都会拼进url里,可以看最下方service调用类的例子,就拼了参数
    public static String get(String url) throws IOException {  
        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方法  
    public static String getWithHeaders(String url, Headers headers) throws IOException {  
        Request request = new Request.Builder()  
                .url(url)  
                .headers(headers)  
                .build();  
  
        try (Response response = client.newCall(request).execute()) {  
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);  
            return response.body().string();  
        }  
    } 
 
    // POST方法:  
    public static String post(String url, String json) throws IOException {  
        RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));  
        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();  
        }  
    }  

    // PUT 方法  
    public static String put(String url, String json) throws IOException {  
        RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));  
        Request request = new Request.Builder()  
                .url(url)  
                .put(body)  
                .build();  
  
        try (Response response = client.newCall(request).execute()) {  
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);  
            return response.body().string();  
        }  
    }  
  
    // DELETE 方法  
    public static String delete(String url) throws IOException {  
        Request request = new Request.Builder()  
                .url(url)  
                .delete()  
                .build();  
  
        try (Response response = client.newCall(request).execute()) {  
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);  
            return response.body().string();  
        }  
    }  
  
}

3.使用OkHttp工具类

现在,你可以在你的Spring Boot应用中的任何地方使用这个工具类来发送HTTP请求。例如,在一个服务类中:

java 复制代码
import org.springframework.stereotype.Service;  

import java.io.IOException;  

@Service  
public class MyService {  

    public void someMethod() {  
        //不带参数直接请求(一般用不到)
        //String url = "https://api.example.com/data";  

        //下方为带参数的情况
        String baseUrl = "https://api.example.com/data";  
        String param1 = "value1";  
        String param2 = "value2";  
  
        // 使用HttpUrl.Builder构建带有查询参数的URL  
        HttpUrl.Builder urlBuilder = HttpUrl.parse(baseUrl).newBuilder();  
        urlBuilder.addQueryParameter("param1", param1);  
        urlBuilder.addQueryParameter("param2", param2);  
        String url = urlBuilder.build().toString();
        //也可以不用HttpUrl类,直接自己用stringbuiler拼接带参数的String字符串,效率差不多
        try {  
            String response = OkHttpUtil.get(url);  
            // 处理响应  
            System.out.println(response);  
        } catch (IOException e) {  
            // 处理异常  
            e.printStackTrace();  
        }  
    }  
}

以上为最基本的请求工具类与示例,可自行增加注释、返回值处理等内容

相关推荐
知识分享小能手7 分钟前
MongoDB入门学习教程,从入门到精通,MongoDB事务知识点梳理(8)
数据库·学习·mongodb
LaughingZhu9 分钟前
Product Hunt 每日热榜 | 2026-03-29
数据库·人工智能·经验分享·神经网络·chatgpt
jialan7514 分钟前
不干胶管理
大数据·数据库
EasyCVR20 分钟前
插件模块化集成设计:花屏蓝屏画面模糊检测...EasyCVR视频质量诊断功能的技术与落地逻辑
服务器·数据库·音视频·视频质量诊断
|华|20 分钟前
mysql的备份与恢复
数据库·mysql
java资料站32 分钟前
milvus向量数据库
数据库·milvus
chushiyunen38 分钟前
langgraph笔记
数据库·人工智能·笔记
切糕师学AI39 分钟前
PostgreSQL 中的 pg_trgm GIN 索引详解
数据库·postgresql·gin·索引·pg_grgm
爱丽_43 分钟前
MySQL 锁与死锁:行锁、间隙锁、Next-Key Lock 与排查手册
数据库·mysql
皙然1 小时前
Redis 持久化机制超详细详解(RDB+AOF 双方案 + 生产实战)
数据库·redis·bootstrap