Java工具类--OkHttp工具类

发布于:2024-10-17 ⋅ 阅读:(6) ⋅ 点赞:(0)

以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。

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请求。例如,在一个服务类中:

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

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