当前位置: 首页 > news >正文

HTTP 接口调用工具类(OkHttp 版)

说明

HTTP 基本知识

序号方法请求体描述
1GET一般没有,可以有从服务器获取资源。用于请求数据而不对数据进行更改。例如,从服务器获取网页、图片等。
2POST向服务器发送数据以创建新资源。常用于提交表单数据或上传文件。发送的数据包含在请求体中。
3PUT向服务器发送数据以更新现有资源。如果资源不存在,则创建新的资源。与 POST 不同,PUT 通常是幂等的,即多次执行相同的 PUT 请求不会产生不同的结果。
4DELETE从服务器删除指定的资源。请求中包含要删除的资源标识符。
5PATCH对资源进行部分修改。与 PUT 类似,但 PATCH 只更改部分数据而不是替换整个资源。
6HEAD类似于 GET,但服务器只返回响应的头部,不返回实际数据。用于检查资源的元数据(例如,检查资源是否存在,查看响应的头部信息)。
7OPTIONS返回服务器支持的 HTTP 方法。用于检查服务器支持哪些请求方法,通常用于跨域资源共享(CORS)的预检请求。
8TRACE回显服务器收到的请求,主要用于诊断。客户端可以查看请求在服务器中的处理路径。
9CONNECT-建立一个到服务器的隧道,通常用于 HTTPS 连接。客户端可以通过该隧道发送加密的数据。

POST、PUT、DELETE、PATCH 一般是有请求体的,GET、HEAD、OPTIONS、TRACE 一般没有请求体(GET 请求其实也可以包含请求体,Spring Boot 也可以接收 GET 请求的请求体),CONNECT 方法并不是直接由用户调用的,而是在建立连接时使用的。

功能

  1. 支持发送 GET、POST、PUT、DELETE、PATCH、HEAD、OPTIONS、TRACE 请求,且均有同步、异步调用方式;

  2. 支持的请求体目前支持常见的 JSON 格式请求体application/json和表单请求体multipart/mixed,表单请求体支持传输 File、InputStream、byte[]类型的(文件)对象;

  3. POST、PUT、DELETE、PATCH 支持以上两种请求体;OkHttp 中,GET 不支持请求体,所以工具类也不支持 GET 请求携带请求体。


代码

引入依赖

 <dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp-jvm</artifactId><version>5.0.0</version></dependency>

注:okhttp 5.x版本,需要引用okhttp-jvm,如果IDEA版本不够新(如2024.1.2),引入okhttp 5.x版本后,idea代码联想可能无法关联上okhttp相关类(实测社区版2025.1.1.1可以)。如果遇到此种情况,可以引入4.x版本,如下:

 <dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.12.0</version></dependency>

HTTP请求类型枚举类

package com.example.study.enums;import lombok.Getter;@Getter
public enum HttpMethodEnum {GET("GET"),POST("POST"),PUT("PUT"),PATCH("PATCH"),DELETE("DELETE"),OPTIONS("OPTIONS"),HEAD("HEAD"),TRACE("TRACE"),CONNECT("CONNECT");private String value;HttpMethodEnum(String value) {this.value = value;}
}

HTTP请求工具类(同步)

package com.example.study.util;import com.alibaba.fastjson.JSON;
import com.example.study.enums.HttpMethodEnum;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.util.StringUtils;import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.TimeUnit;/*** HTTP请求工具类(同步)*/
@Slf4j
public class HttpUtils {private static final MediaType APPLICATION_JSON_UTF8 = MediaType.parse("application/json; charset=utf-8");private static final MediaType APPLICATION_OCTET_STREAM = MediaType.parse("application/octet-stream");private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");private static final OkHttpClient CLIENT = new OkHttpClient.Builder().connectTimeout(2, TimeUnit.MINUTES).readTimeout(2, TimeUnit.MINUTES).writeTimeout(2, TimeUnit.MINUTES).build();/*** 执行get请求** @param url url* @return 请求结果*/public static HttpUtilResponse get(String url) {return get(url, null);}/*** 执行get请求** @param url     url* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse get(String url, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);Request request = builder.get().build();return execute(request);}/*** 执行post请求(请求体为json)** @param url  url* @param body 请求体* @return 请求结果*/public static HttpUtilResponse post(String url, Map<String, Object> body) {return post(url, body, null);}/*** 执行post请求(请求体为json)** @param url     url* @param body    请求体* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse post(String url, Map<String, Object> body, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setJsonBody(builder, body, HttpMethodEnum.POST);Request request = builder.build();return execute(request);}/*** 执行post请求(请求体为form)** @param url  url* @param body 请求体* @return 请求结果*/public static HttpUtilResponse postForm(String url, Map<String, Object> body) {return postForm(url, body, null);}/*** 执行post请求(请求体为form)** @param url     url* @param body    请求体* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse postForm(String url, Map<String, Object> body, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setFormBody(builder, body, HttpMethodEnum.POST);Request request = builder.build();return execute(request);}/*** 执行put请求(请求体为json)** @param url  url* @param body 请求体* @return 请求结果*/public static HttpUtilResponse put(String url, Map<String, Object> body) {return put(url, body, null);}/*** 执行put请求(请求体为json)** @param url     url* @param body    请求体* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse put(String url, Map<String, Object> body, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setJsonBody(builder, body, HttpMethodEnum.PUT);Request request = builder.build();return execute(request);}/*** 执行put请求(请求体为form)** @param url  url* @param body 请求体* @return 请求结果*/public static HttpUtilResponse putForm(String url, Map<String, Object> body) {return putForm(url, body, null);}/*** 执行put请求(请求体为form)** @param url     url* @param body    请求体* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse putForm(String url, Map<String, Object> body, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setFormBody(builder, body, HttpMethodEnum.PUT);Request request = builder.build();return execute(request);}/*** 执行patch请求(请求体为json)** @param url  url* @param body 请求体* @return 请求结果*/public static HttpUtilResponse patch(String url, Map<String, Object> body) {return patch(url, body, null);}/*** 执行patch请求(请求体为json)** @param url     url* @param body    请求体* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse patch(String url, Map<String, Object> body, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setJsonBody(builder, body, HttpMethodEnum.PATCH);Request request = builder.build();return execute(request);}/*** 执行patch请求(请求体为form)** @param url  url* @param body 请求体* @return 请求结果*/public static HttpUtilResponse patchForm(String url, Map<String, Object> body) {return patchForm(url, body, null);}/*** 执行patch请求(请求体为form)** @param url     url* @param body    请求体* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse patchForm(String url, Map<String, Object> body, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setFormBody(builder, body, HttpMethodEnum.PATCH);Request request = builder.build();return execute(request);}/*** 执行delete请求(请求体为json)** @param url  url* @param body 请求体* @return 请求结果*/public static HttpUtilResponse delete(String url, Map<String, Object> body) {return delete(url, body, null);}/*** 执行delete请求(请求体为json)** @param url     url* @param body    请求体* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse delete(String url, Map<String, Object> body, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setJsonBody(builder, body, HttpMethodEnum.DELETE);Request request = builder.build();return execute(request);}/*** 执行delete请求(请求体为form)** @param url  url* @param body 请求体* @return 请求结果*/public static HttpUtilResponse deleteForm(String url, Map<String, Object> body) {return deleteForm(url, body, null);}/*** 执行delete请求(请求体为form)** @param url     url* @param body    请求体* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse deleteForm(String url, Map<String, Object> body, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setFormBody(builder, body, HttpMethodEnum.DELETE);Request request = builder.build();return execute(request);}/*** 执行options请求** @param url url* @return 请求结果*/public static HttpUtilResponse options(String url) {return options(url, null);}/*** 执行options请求** @param url     url* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse options(String url, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);Request request = builder.method(HttpMethodEnum.OPTIONS.getValue(), null).build();return execute(request);}/*** 执行head请求** @param url url* @return 请求结果*/public static HttpUtilResponse head(String url) {return head(url, null);}/*** 执行head请求** @param url     url* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse head(String url, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);Request request = builder.head().build();return execute(request);}/*** 执行trace请求** @param url url* @return 请求结果*/public static HttpUtilResponse trace(String url) {return trace(url, null);}/*** 执行trace请求** @param url     url* @param headers 请求头* @return 请求结果*/public static HttpUtilResponse trace(String url, Map<String, String> headers) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);Request request = builder.method(HttpMethodEnum.TRACE.getValue(), null).build();return execute(request);}private static void setHeaders(Request.Builder builder, Map<String, String> headers) {if (headers != null) {log.info("request headers:{}", JSON.toJSONString(headers));builder.headers(Headers.of(headers));}}private static void setJsonBody(Request.Builder builder, Map<String, Object> body, HttpMethodEnum method) {if (body == null) {return;}String jsonBody = JSON.toJSONString(body);log.info("request body json:{}", jsonBody);RequestBody requestBody = RequestBody.create(jsonBody, APPLICATION_JSON_UTF8);switch (method) {case PUT -> builder.put(requestBody);case POST -> builder.post(requestBody);case PATCH -> builder.patch(requestBody);case DELETE -> builder.delete(requestBody);}}private static void setFormBody(Request.Builder builder, Map<String, Object> body, HttpMethodEnum method) {if (body == null) {return;}MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder();for (Map.Entry<String, Object> entry : body.entrySet()) {if (entry.getKey() == null || entry.getValue() == null) {continue;}if (entry.getValue() instanceof File file) {log.info("form body {} is File.", entry.getKey());requestBodyBuilder.addFormDataPart(entry.getKey(), file.getName(), RequestBody.create(file,APPLICATION_OCTET_STREAM));} else if (entry.getValue() instanceof InputStream is) {try {log.info("form body {} is InputStream.", entry.getKey());requestBodyBuilder.addFormDataPart(entry.getKey(), entry.getKey(), RequestBody.create(is.readAllBytes(),APPLICATION_OCTET_STREAM));} catch (IOException exception) {throw new RuntimeException(exception.getMessage());}} else if (entry.getValue() instanceof byte[] bytes) {log.info("form body {} is byte[].", entry.getKey());requestBodyBuilder.addFormDataPart(entry.getKey(), entry.getKey(), RequestBody.create(bytes,APPLICATION_OCTET_STREAM));} else if (entry.getValue() instanceof String value) {log.info("form body {} is String. value:{}", entry.getKey(), value);requestBodyBuilder.addFormDataPart(entry.getKey(), value);} else {log.info("form body {} is {}. value:{}", entry.getKey(), entry.getValue().getClass(), entry.getValue());requestBodyBuilder.addFormDataPart(entry.getKey(), String.valueOf(entry.getValue()));}}RequestBody requestBody = requestBodyBuilder.build();switch (method) {case PUT -> builder.put(requestBody);case POST -> builder.post(requestBody);case PATCH -> builder.patch(requestBody);case DELETE -> builder.delete(requestBody);}}private static HttpUtilResponse execute(Request request) {log.info("{} =====start send {} request. url:{}=====", timestamp(), request.method(), request.url());long startTime = System.currentTimeMillis();try (Response response = CLIENT.newCall(request).execute()) {log.info("{} =====send {} request success. url:{}, spend {}ms=====", timestamp(), request.method(),request.url(), (System.currentTimeMillis() - startTime));return new HttpUtilResponse(response.headers(), response.body().bytes());} catch (IOException exception) {log.error("{} =====send {} request fail. url:{}, spend {}ms=====", timestamp(), request.method(),request.url(), (System.currentTimeMillis() - startTime));throw new RuntimeException(String.format("send %s request fail. url:%s, reason:%s", request.method(),request.url(), exception.getMessage()));}}private static String timestamp() {return FORMATTER.format(LocalDateTime.now());}
}

HTTP请求工具类(异步)

package com.example.study.util;import com.alibaba.fastjson.JSON;
import com.example.study.enums.HttpMethodEnum;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.util.StringUtils;import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.TimeUnit;/*** HTTP请求工具类(异步)*/
@Slf4j
public class HttpAsyncUtils {private static final MediaType APPLICATION_JSON_UTF8 = MediaType.parse("application/json; charset=utf-8");private static final MediaType APPLICATION_OCTET_STREAM = MediaType.parse("application/octet-stream");private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");private static final OkHttpClient CLIENT = new OkHttpClient.Builder().connectTimeout(2, TimeUnit.MINUTES).readTimeout(2, TimeUnit.MINUTES).writeTimeout(2, TimeUnit.MINUTES).build();/*** 执行get请求** @param url      url* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse get(String url, Callback callback) {return get(url, null, callback);}/*** 执行get请求** @param url      url* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse get(String url, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);Request request = builder.get().build();return execute(request);}/*** 执行post请求(请求体为json)** @param url      url* @param body     请求体* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse post(String url, Map<String, Object> body, Callback callback) {return post(url, body, null, callback);}/*** 执行post请求(请求体为json)** @param url      url* @param body     请求体* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse post(String url, Map<String, Object> body, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setJsonBody(builder, body, HttpMethodEnum.POST);Request request = builder.build();return execute(request);}/*** 执行post请求(请求体为form)** @param url      url* @param body     请求体* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse postForm(String url, Map<String, Object> body, Callback callback) {return postForm(url, body, null, callback);}/*** 执行post请求(请求体为form)** @param url      url* @param body     请求体* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse postForm(String url, Map<String, Object> body, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setFormBody(builder, body, HttpMethodEnum.POST);Request request = builder.build();return execute(request);}/*** 执行put请求(请求体为json)** @param url      url* @param body     请求体* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse put(String url, Map<String, Object> body, Callback callback) {return put(url, body, null, callback);}/*** 执行put请求(请求体为json)** @param url      url* @param body     请求体* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse put(String url, Map<String, Object> body, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setJsonBody(builder, body, HttpMethodEnum.PUT);Request request = builder.build();return execute(request);}/*** 执行put请求(请求体为form)** @param url      url* @param body     请求体* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse putForm(String url, Map<String, Object> body, Callback callback) {return putForm(url, body, null, callback);}/*** 执行put请求(请求体为form)** @param url      url* @param body     请求体* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse putForm(String url, Map<String, Object> body, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setFormBody(builder, body, HttpMethodEnum.PUT);Request request = builder.build();return execute(request);}/*** 执行patch请求(请求体为json)** @param url      url* @param body     请求体* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse patch(String url, Map<String, Object> body, Callback callback) {return patch(url, body, null, callback);}/*** 执行patch请求(请求体为json)** @param url      url* @param body     请求体* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse patch(String url, Map<String, Object> body, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setJsonBody(builder, body, HttpMethodEnum.PATCH);Request request = builder.build();return execute(request);}/*** 执行patch请求(请求体为form)** @param url      url* @param body     请求体* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse patchForm(String url, Map<String, Object> body, Callback callback) {return patchForm(url, body, null, callback);}/*** 执行patch请求(请求体为form)** @param url      url* @param body     请求体* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse patchForm(String url, Map<String, Object> body, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setFormBody(builder, body, HttpMethodEnum.PATCH);Request request = builder.build();return execute(request);}/*** 执行delete请求(请求体为json)** @param url      url* @param body     请求体* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse delete(String url, Map<String, Object> body, Callback callback) {return delete(url, body, null, callback);}/*** 执行delete请求(请求体为json)** @param url      url* @param body     请求体* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse delete(String url, Map<String, Object> body, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setJsonBody(builder, body, HttpMethodEnum.DELETE);Request request = builder.build();return execute(request);}/*** 执行delete请求(请求体为form)** @param url      url* @param body     请求体* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse deleteForm(String url, Map<String, Object> body, Callback callback) {return deleteForm(url, body, null, callback);}/*** 执行delete请求(请求体为form)** @param url      url* @param body     请求体* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse deleteForm(String url, Map<String, Object> body, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);setFormBody(builder, body, HttpMethodEnum.DELETE);Request request = builder.build();return execute(request);}/*** 执行options请求** @param url      url* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse options(String url, Callback callback) {return options(url, null, callback);}/*** 执行options请求** @param url      url* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse options(String url, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);Request request = builder.method(HttpMethodEnum.OPTIONS.getValue(), null).build();return execute(request);}/*** 执行head请求** @param url      url* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse head(String url, Callback callback) {return head(url, null, callback);}/*** 执行head请求** @param url      url* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse head(String url, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);Request request = builder.head().build();return execute(request);}/*** 执行trace请求** @param url      url* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse trace(String url, Callback callback) {return trace(url, null, callback);}/*** 执行trace请求** @param url      url* @param headers  请求头* @param callback 请求成功后的回调函数* @return 请求结果*/public static HttpUtilResponse trace(String url, Map<String, String> headers, Callback callback) {if (!StringUtils.hasText(url)) {throw new RuntimeException("url must not be null");}if (callback == null) {throw new RuntimeException("callback must not be null");}Request.Builder builder = new Request.Builder().url(url);setHeaders(builder, headers);Request request = builder.method(HttpMethodEnum.TRACE.getValue(), null).build();return execute(request);}private static void setHeaders(Request.Builder builder, Map<String, String> headers) {if (headers != null) {log.info("request headers:{}", JSON.toJSONString(headers));builder.headers(Headers.of(headers));}}private static void setJsonBody(Request.Builder builder, Map<String, Object> body, HttpMethodEnum method) {if (body == null) {return;}String jsonBody = JSON.toJSONString(body);log.info("request body json:{}", jsonBody);RequestBody requestBody = RequestBody.create(jsonBody, APPLICATION_JSON_UTF8);switch (method) {case PUT -> builder.put(requestBody);case POST -> builder.post(requestBody);case PATCH -> builder.patch(requestBody);case DELETE -> builder.delete(requestBody);}}private static void setFormBody(Request.Builder builder, Map<String, Object> body, HttpMethodEnum method) {if (body == null) {return;}MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder();for (Map.Entry<String, Object> entry : body.entrySet()) {if (entry.getKey() == null || entry.getValue() == null) {continue;}if (entry.getValue() instanceof File file) {log.info("form body {} is File.", entry.getKey());requestBodyBuilder.addFormDataPart(entry.getKey(), file.getName(), RequestBody.create(file,APPLICATION_OCTET_STREAM));} else if (entry.getValue() instanceof InputStream is) {try {log.info("form body {} is InputStream.", entry.getKey());requestBodyBuilder.addFormDataPart(entry.getKey(), entry.getKey(), RequestBody.create(is.readAllBytes(),APPLICATION_OCTET_STREAM));} catch (IOException exception) {throw new RuntimeException(exception.getMessage());}} else if (entry.getValue() instanceof byte[] bytes) {log.info("form body {} is byte[].", entry.getKey());requestBodyBuilder.addFormDataPart(entry.getKey(), entry.getKey(), RequestBody.create(bytes,APPLICATION_OCTET_STREAM));} else if (entry.getValue() instanceof String value) {log.info("form body {} is String. value:{}", entry.getKey(), value);requestBodyBuilder.addFormDataPart(entry.getKey(), value);} else {log.info("form body {} is {}. value:{}", entry.getKey(), entry.getValue().getClass(), entry.getValue());requestBodyBuilder.addFormDataPart(entry.getKey(), String.valueOf(entry.getValue()));}}RequestBody requestBody = requestBodyBuilder.build();switch (method) {case PUT -> builder.put(requestBody);case POST -> builder.post(requestBody);case PATCH -> builder.patch(requestBody);case DELETE -> builder.delete(requestBody);}}private static HttpUtilResponse execute(Request request) {log.info("{} =====start send {} request. url:{}=====", timestamp(), request.method(), request.url());long startTime = System.currentTimeMillis();try (Response response = CLIENT.newCall(request).execute()) {log.info("{} =====send {} request success. url:{}, spend {}ms=====", timestamp(), request.method(),request.url(), (System.currentTimeMillis() - startTime));return new HttpUtilResponse(response.headers(), response.body().bytes());} catch (IOException exception) {log.error("{} =====send {} request fail. url:{}, spend {}ms=====", timestamp(), request.method(),request.url(), (System.currentTimeMillis() - startTime));throw new RuntimeException(String.format("send %s request fail. url:%s, reason:%s", request.method(),request.url(), exception.getMessage()));}}private static String timestamp() {return FORMATTER.format(LocalDateTime.now());}
}
http://www.xdnf.cn/news/1357489.html

相关文章:

  • 华为网路设备学习-30(BGP协议 五)Community、
  • pytorch线性回归(二)
  • elasticsearch 7.x elasticsearch 使用scroll滚动查询中超时问题案例
  • MySQL官方C/C++ 接口入门
  • Ubuntu24.04 安装 Zabbix
  • ComfyUI ZLUDA AMD conda 使用遇到的问题
  • rust语言 (1.88) egui (0.32.1) 学习笔记(逐行注释)(十五)网格布局
  • 【229页PPT】某大型制药集团企业数字化转型SAP蓝图设计解决方案(附下载方式)
  • 目标检测数据集 第006期-基于yolo标注格式的汽车事故检测数据集(含免费分享)
  • 网络协议UDP、TCP
  • 管道符在渗透测试与网络安全中的全面应用指南
  • 【信息安全】英飞凌TC3xx安全调试口功能实现(调试口保护)
  • OSG库子动态库和插件等文件介绍
  • AlmaLinux 上 Python 3.6 切换到 Python 3.11
  • 从 JUnit 深入理解 Java 注解与反射机制
  • Flink元空间异常深度解析:从原理到实战调优指南
  • 数字防线:现代企业网络安全运维实战指南
  • Maven项目中settings.xml终极优化指南
  • 得物25年春招-安卓部分笔试题1
  • Flink 实时加购数据“维表补全”实战:从 Kafka 到 HBase 再到 Redis 的完整链路
  • GaussDB 数据库架构师修炼(十八) SQL引擎-分布式计划
  • vimware unbuntu18.04 安装之后,没有网络解决方案
  • AI与SEO关键词协同优化
  • 【小程序-慕尚花坊02】网络请求封装和注意事项
  • 个人搭建小网站教程(云服务器Ubuntu版本)
  • 不知道Pycharm怎么安装?Pycharm安装教程(附安装包)
  • MySQL數據庫開發教學(二) 核心概念、重要指令
  • GaussDB 数据库架构师修炼(十八) SQL引擎-统计信息
  • 请求上下文对象RequestContextHolder
  • LIANA | part2 results部分