From 0ee69fa2b20da4a5de42aa4f6a7a2f32f576da53 Mon Sep 17 00:00:00 2001 From: JianYu Zheng <2375294554@qq.com> Date: Wed, 25 Jun 2025 11:06:36 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86http=E5=8F=91?= =?UTF-8?q?=E9=80=81=E5=B7=A5=E5=85=B7=E7=B1=BB=20--HttpSendUtils.java=20?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E5=8F=91=E9=80=81get=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=EF=BC=8C=E8=8E=B7=E5=8F=96=E8=BF=94=E5=9B=9E=E7=9A=84?= =?UTF-8?q?body=E8=BD=AC=E6=8D=A2=E6=88=90=E5=AD=97=E7=AC=A6=E4=B8=B2=20?= =?UTF-8?q?=E6=96=B9=E6=B3=95=20=E5=8F=91=E9=80=81post=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=EF=BC=8C=E5=8F=82=E6=95=B0=E4=B8=BAjson=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E3=80=82=E5=8F=96=E8=BF=94=E5=9B=9E=E7=9A=84body=E8=BD=AC?= =?UTF-8?q?=E6=8D=A2=E6=88=90=E5=AD=97=E7=AC=A6=E4=B8=B2=20=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xiaozhi/common/utils/HttpSendUtils.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/HttpSendUtils.java diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/HttpSendUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/HttpSendUtils.java new file mode 100644 index 00000000..0e3429e7 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/HttpSendUtils.java @@ -0,0 +1,64 @@ +package xiaozhi.common.utils; + +import lombok.extern.slf4j.Slf4j; +import okhttp3.*; +import org.jetbrains.annotations.Nullable; +import org.springframework.stereotype.Component; +import xiaozhi.common.exception.RenException; + +import java.io.IOException; + +@Slf4j +@Component +public class HttpSendUtils { + private OkHttpClient client = new OkHttpClient(); + + /** + * 发送get请求,获取返回的body转换成字符串 + * @param url get请求地址 + * @return body内容 + */ + public String fetchGetBodyAsString(String url) { + Request request = new Request.Builder() + .url(url) + .build(); + return getString(url, request); + } + + /** + * 发送post请求,参数为json格式。取返回的body转换成字符串 + * @param url post请求地址 + * @param json json参数 + * @return body内容 + */ + public String fetchJsonPostBodyAsString(String url,String json) { + // 创建请求体 + MediaType JSON = MediaType.get("application/json; charset=utf-8"); + RequestBody body = RequestBody.create(json, JSON); + + Request request = new Request.Builder() + .url(url) + .post(body) + .build(); + + return getString(url, request); + } + + private String getString(String url, Request request) { + String body = null; + try (Response response = client.newCall(request).execute()) { + if (response.isSuccessful()) { + if (response.body() != null){ + body = response.body().string(); + } + } else { + throw new RenException("请求失败,错误码:"+response.code()); + } + } catch (Exception e) { + String method = request.method(); + log.error("{}请求发送错误地址:{} \n 发送错误信息:{}",method, url,e.getMessage()); + throw new RenException("请求发送失败"); + } + return body; + } +}