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

互联网建站网站wordpress插件留言墙

互联网建站网站,wordpress插件留言墙,深圳建设集团有限公司地址,下载重庆人社app说明 HTTP 基本知识序号方法请求体描述1GET一般没有,可以有从服务器获取资源。用于请求数据而不对数据进行更改。例如,从服务器获取网页、图片等。2POST有向服务器发送数据以创建新资源。常用于提交表单数据或上传文件。发送的数据包含在请求体中。3PUT有…

说明

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.dtcms.com/a/531571.html

相关文章:

  • 2小时wordpress建站wordpress可视化文章
  • 保定制作公司网站凡客诚品官网网址
  • 为什么我的网站没有百度索引量张掖网站设计公司
  • wordpress开启子域名多站贷款网站建设方案
  • 北京高端网站tk域名注册官网
  • 无法连接到wordpress站点做网站国内好的服务器
  • 引导式网站北京广告制作公司
  • 天津网站建设座机号做视频网站容易收录吗
  • 自己做网站自己买服务器已购买域名 如何做网站
  • wordpress建站需要多久ppt模板app
  • 太原网站网络推广wordpress上传到哪个文件夹
  • 合肥建站推广php与 wordpress
  • 资讯文章网站模板wordpress inc文件夹
  • 查网站权重佛山住建
  • 可以做相册的网站线上推广渠道和方式
  • 关于未备案网站电子商务网站网络安全设计方案
  • 北京网站开发网站建设报价青岛制作网站哪家公司好
  • wordpress网站缩进口博览会2022
  • 皮肤自做头像的网站沈阳 网站建设
  • 孝感网站开发网订率推广技巧
  • 天津网站建设icp备wordpress底部导航代码
  • 定制彩票网站开发免费制作壁纸的app
  • 企业网站建设费用入哪个科目自考大型网站开发工具
  • 个人网站 阿里云如何建议一个网站
  • 普陀网站建设哪家好网站核验点
  • c2c电子商务网站腾讯企业邮箱怎么注册
  • node 网站开发 视频教程设计好的装修公司
  • 电影网站开发api网站备案完成通知书
  • 自己做网站和推广word上下页边距不见了
  • 合肥高端网站建设西宁企业网站开发定制