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();  
        }  
    }  
}

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

相关推荐
RestCloud11 小时前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud11 小时前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence13 小时前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger20 小时前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥1 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud1 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术2 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
可涵不会debug2 天前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom2 天前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试
麦兜*2 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud