引入okHttp依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
自定义HttpUtil工具类
@Slf4j
public class HttpUtil {
private static OkHttpClient client = new OkHttpClient().newBuilder()
.callTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
public static String get(String url){
Response execute = null;
Request request = new Request.Builder()
.method("GET",null)
.url(url)
.build();
try {
execute = client.newCall(request).execute();
if (ObjectUtil.isNotNull(execute) && execute.isSuccessful()){
return execute.body().string();
}
} catch (IOException e) {
log.error("http get 请求失败--{}",e);
}
return null;
}
public static byte[] getBytes(String url){
Response execute = null;
Request request = new Request.Builder()
.method("GET",null)
.url(url)
.build();
try {
execute = client.newCall(request).execute();
if (ObjectUtil.isNotNull(execute) && execute.isSuccessful()){
return execute.body().bytes();
}
} catch (IOException e) {
log.error("http get 请求失败--{}",e);
}
return null;
}
public static String post(String url,String body){
Response execute = null;
Request request = new Request.Builder()
.method("POST", RequestBody.create(body, MediaType.get("application/json")))
.url(url)
.build();
try {
execute = client.newCall(request).execute();
if (ObjectUtil.isNotNull(execute) && execute.isSuccessful()){
return execute.body().string();
}
} catch (IOException e) {
log.error("http post 请求失败--{}",e);
}
return null;
}
}