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

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

相关推荐
格调UI成品2 小时前
预警系统安全体系构建:数据加密、权限分级与误报过滤方案
大数据·运维·网络·数据库·安全·预警
心平愈三千疾6 小时前
通俗理解JVM细节-面试篇
java·jvm·数据库·面试
我科绝伦(Huanhuan Zhou)9 天前
Oracle|Oracle SQL*Plus 配置上下翻页功能
数据库·sql·oracle
Cachel wood9 天前
Spark教程6:Spark 底层执行原理详解
大数据·数据库·分布式·计算机网络·spark
java—大象9 天前
基于java SSM的房屋租赁系统设计和实现
java·开发语言·数据库·spring boot·layui·mybatis
Mutig_s9 天前
Spring Boot动态数据源切换:优雅实现多数据源管理
java·数据库·spring boot·后端·mybatis
Python小老六9 天前
单片机测ntc热敏电阻的几种方法(软件)
数据库·单片机·嵌入式硬件
矿渣渣9 天前
SQLite3 在嵌入式系统中的应用指南
数据库·sqlite·嵌入式实时数据库
@昵称不存在9 天前
Python csv 模块
开发语言·数据库·python
程序猿小D9 天前
[附源码+数据库+毕业论文]基于Spring+MyBatis+MySQL+Maven+Vue实现的校园二手交易平台管理系统,推荐!
java·数据库·mysql·spring·vue·毕业设计·校园二手交易平台