package com.k8s.demo.utils;
import com.alibaba.fastjson.JSON;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.util.concurrent.TimeUnit;
/**
* Author: 徐寿春
* Date: 2024/2/28 19:10
* <p>
* 名称
*/
@Slf4j
@NoArgsConstructor
public class OkHttpUtil {
public static final String MEDIA_TYPE_JSON = "application/json; charset=utf-8";
private static final OkHttpClient okHttpClient;
static int connectTimeout = 60;
static int readTimeout = 60;
static int writeTimeout = 60;
static {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
builder.readTimeout(readTimeout, TimeUnit.SECONDS);
builder.writeTimeout(writeTimeout, TimeUnit.SECONDS);
okHttpClient = builder.build();
}
public static OkHttpClient getOkHttpClient() {
return okHttpClient;
}
/**
* GET请求。使用默认的 okHttpClient 和 headers
*
* @param url
* @return
*/
public static String get(String url) {
OkHttpClient okHttpClient = getOkHttpClient();
Headers headers = new Headers.Builder().build();
return get(okHttpClient, url, headers);
}
/**
* post请求。使用默认的 okHttpClient 和 headers
*
* @param url
* @param bodyJson
* @return
*/
public static String post(String url, Object bodyJson) {
OkHttpClient okHttpClient = getOkHttpClient();
Headers headers = new Headers.Builder().build();
return post(okHttpClient, url, bodyJson, headers);
}
/**
* 获取响应结果
*
* @param okHttpClient
* @param url
* @param request
* @return
*/
public static String request(OkHttpClient okHttpClient, String url, Request request) {
String responseData = "";
try (Response response = okHttpClient.newCall(request).execute()) {
if (response.body() != null) {
return response.body().string();
}
} catch (Exception e) {
log.error("okHttpClient getResponse error.url:{}", url, e);
}
return responseData;
}
/**
* get请求
*
* @param okHttpClient
* @param url
* @param headers header参数
* @return
*/
public static String get(OkHttpClient okHttpClient, String url, Headers headers) {
Request request = new Request.Builder().url(url).headers(headers).get().build();
return request(okHttpClient, url, request);
}
/**
* post请求,获取响应结果
*
* @param okHttpClient
* @param url
* @param bodyJson
* @param headers
* @return
*/
public static String post(OkHttpClient okHttpClient, String url, Object bodyJson, Headers headers) {
log.info("okHttpClient post url:{}, body====> {}", url, bodyJson);
MediaType mediaTypeJson = MediaType.parse(MEDIA_TYPE_JSON);
RequestBody requestBody = RequestBody.create(mediaTypeJson, JSON.toJSONString(bodyJson));
Request request = new Request.Builder().url(url).headers(headers).post(requestBody).build();
String responseData = request(okHttpClient, url, request);
log.info("okHttpClient post url:{},post responseData====> {}", url, responseData);
return responseData;
}
}
05-15
853
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)