- Maven依赖pom:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
- 代码:
package com.c2f.hbos.agent.plugin.charge.common.utils;
import lombok.Getter;
import lombok.NonNull;
import okhttp3.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
/**
* @description: OkHttp工具类
* @author: Yang JianXiong
* @since: 2022/10/25
*/
public interface OkHttpUtil {
/**
* JSON POST
*
* @param url
* @param json
* @return
*/
static String jsonPost(@NonNull String url, @NonNull String json) {
RequestBody requestBody = RequestBody.create(json.getBytes(StandardCharsets.UTF_8), MediaType.parse("application/json;charset=utf-8"));
Request request = new Request.Builder().url(url).post(requestBody).build();
try {
Response response = OkHttpClient.CLIENT.getInstance().newCall(request).execute();
if (response.isSuccessful()) {
//字节流
//return response.body().byteStream();
//字符串
return response.body().toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@Getter
enum OkHttpClient {
/**
* 客户端实例
*/
CLIENT(new okhttp3.OkHttpClient.Builder()
.retryOnConnectionFailure(false)
.connectionPool(new ConnectionPool(200, 47, TimeUnit.MINUTES))
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build());
private final okhttp3.OkHttpClient instance;
OkHttpClient(okhttp3.OkHttpClient instance) {
this.instance = instance;
}
}
标签:集成,return,okhttp3,OkHttpClient,instance,okHttp3,TimeUnit,import
From: https://www.cnblogs.com/JaxYoun/p/16826687.html