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

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

相关推荐
名字还没想好☜8 小时前
Python f-string 进阶:数字格式化、对齐填充、调试 = 号与嵌套表达式
开发语言·数据库·python·字符串格式化·f-string
ltl8 小时前
Serverless 数据库弹性理论:Neon 与 Aurora Serverless v2
数据库
marvelyu13 小时前
每天10分钟学会OceanBase系列(Day 20):跨机房容灾实战——构建多数据中心高可用架构
java·大数据·数据库
ZCBUS实时计算13 小时前
金融证券实时数仓建设实践:轻量化实时计算平台落地,实现交易数据端到端秒级处理
大数据·数据库·数据仓库·金融·flink·dba·etl
zd20057213 小时前
海洋微生物数据库
数据库·宏基因组
海上小飞龙14 小时前
Redis 分布式锁原理:从 SET NX EX 到 Redisson 看门狗
数据库·redis·分布式
xiaoye-duck14 小时前
MySQL 表约束全解:从基础约束到外键关联规则
数据库·mysql
Hammer_Hans14 小时前
DFT笔记98
java·开发语言·数据库
迪康Defender15 小时前
从静态存储到动态流转:终端透明加密两种模式实战解析
运维·服务器·网络·数据库·其他
2601_9657984715 小时前
Is Piroll WordPress Theme Worth It for Freelancers? Full Review
数据库·php