Java工具类--OkHttp工具类

devtools/2024/10/24 6:16:50/

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

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


http://www.ppmy.cn/devtools/128380.html

相关文章

elementUi el-table 表头高度异常问题

1、现象 在同一个页面通过状态切换不同table时&#xff0c;当从有合并标头行的table切换到无合并表头的table时&#xff0c;无合并表头的table的表头的高度异常了&#xff0c;如下图 切换后 2、解决 给每个el-table 加上一个唯一的key <el-table key"1"></…

国内动态短效sk5

HTTP爬虫代理,软件测试&#xff0c;全高匿名&#xff0c;私密IP&#xff0c;支持API 指路小熊IP https://www.xiaoxiongip.com?fromqkJWgD可测

Python re 模块:正则表达式的强大工具

文章目录 Python re 模块&#xff1a;正则表达式的强大工具导入 re 模块基本匹配方法re.match()re.search()re.findall()re.finditer() 替换操作re.sub() 分割字符串re.split() 捕获组和非捕获组捕获组非捕获组 常用模式符号实际应用示例验证电子邮件格式提取 URL 预定义字符简…

Qt中使用线程之QRunnable

1、自定义1个子类继承自QRunnable 2、重写run方法&#xff0c;编写子线程的业务逻辑 3、使用QThreadPool的全局方法来开启这个线程 4、线程的回收不需要关注&#xff0c;由QThreadPool处理 5、缺点&#xff1a;无法使用信号槽机制 6、适合一些不需要和主线程通信的耗时的任…

C#中的LINQ之美:优雅的数据查询与操作

LINQ&#xff08;Language Integrated Query&#xff0c;语言集成查询&#xff09;是C#中一个强大的工具&#xff0c;它将查询功能直接融入到语言中&#xff0c;使开发者能够以一种更直观、更接近自然语言的方式来操作数据。LINQ不仅能极大地提高开发效率&#xff0c;而且让代码…

欧盟 RED 网络安全法规 EN 18031

目录 1. &#x1f4c2; EN 18031 1.1 背景 1.2 专业术语 1.3 覆盖产品范围 1.4 EN 18031标准主要评估内容&#xff1a; 1.5 EN 18031标准主要评估项目&#xff1a; 1.6 EN 18031 与 ETSI EN 303 645 的主要差异 1.7 RED 网络安全法规解读研讨会 2. &#x1f531; EN 1…

安全见闻(7)——开阔眼界,不做井底之蛙

内容预览 ≧∀≦ゞ 安全见闻七&#xff1a;洞悉硬件设备的安全风险声明导语硬件设备的安全问题物理安全问题设备被盗或损坏环境因素电磁干扰 供应链安全问题假冒伪劣产品恶意软件植入供应链中断 设备漏洞问题操作系统漏洞固件漏洞硬件设计漏洞 网络连接问题网络攻击无线连接安全…

Windows系统PyCharm右键运行.sh文件

在参考了Windows系统下pycharm运行.sh文件&#xff0c;执行shell命令_shell在pycharm-CSDN博客 和深度学习&#xff1a;PyCharm中运行Bash脚本_pycharm bash-CSDN博客 配置了右键执行.sh文件之后&#xff0c;发现在Windows的PyCharm中直接右键运行sh文件&#xff0c;存在如下…