public class RestClientUtils {
private static volatile RestClient restClient = null;
final static TrustManager TRUST_ALL_CERTS = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
log.info("all trusted");
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
log.info("no need to Trusted");
}
};
static {
SslContext sslContext = null;
try {
sslContext = SslContextBuilder.forClient().trustManager(TRUST_ALL_CERTS).build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
SslProvider build = SslProvider.builder().sslContext(sslContext).build();
restClient = RestClient
.builder()
.requestFactory(new ReactorNettyClientRequestFactory(HttpClient.create().secure(build)))
// .baseUrl("https://"+myIp)
.build();
}
public RestClientUtils() {
}
// get 请求示例
public static JSONObject get(String urlString,String header) {
log.info("执行get请求>>url为{}请求头为{}",urlString,header);
return restClient
.get()
.uri(urlString)
.headers(httpHeaders -> httpHeaders.add(HttpHeaders.AUTHORIZATION,header))
.retrieve()
.body(JSONObject.class);
}
/**
* @param urlString 请求URL
* @param body post请求 body
* @param authHeaders 请求头参数
* @return
*/
public static JSONObject jsonPostHeader(String urlString, JSONObject body, String authHeaders) {
log.info("执行jsonPost请求>>url为{}请求体为{},请求头为{}",urlString,body,authHeaders);
return restClientGo(urlString,HttpMethod.POST,MediaType.APPLICATION_JSON,body,Map.of(HttpHeaders.AUTHORIZATION,authHeaders));
}
public static JSONObject restClientGo(String urlString, HttpMethod httpMethod, MediaType mediaType,JSONObject body,Map<String, String> headers) {
log.info("执行restClientGo请求>>url为{}请求体为{}",urlString,body);
return restClient
.method(httpMethod)
.uri(urlString)
.headers(httpHeaders -> headers.forEach(httpHeaders::add))
.accept(mediaType)
.body(body)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {
throw new ProfileBusinessException(response.getStatusCode().value(), response.getStatusText());
})
.onStatus(HttpStatusCode::is5xxServerError, (request, response) -> {
throw new ProfileBusinessException(response.getStatusCode().value(), response.getStatusText());
})
.body(JSONObject.class);
}
}
spring boot 3.2 使用 restclient 使用 ReactorNettyClientRequestFactory 作为请求创建工厂 忽略SSL
最新推荐文章于 2024-05-15 17:52:33 发布