httpCLient请求工具类封装
1、okhttp工具类
依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
</dependencies>
工具类
package com.example.okhttp.utils;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* @Description: okhttp工具类
* @author: lh
*/
public class OkHttpUtils {
private static volatile OkHttpClient okHttpClient = null;
private static volatile Semaphore semaphore = null;
private Map<String, String> headerMap;
private Map<String, String> paramMap;
private String url;
private Request.Builder request;
/**
* 初始化okHttpClient,并且允许https访问
*/
private OkHttpUtils() {
if (okHttpClient == null) {
synchronized (OkHttpClient.class) {
if (okHttpClient == null) {
// 设置代理方式
// Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
TrustManager[] trustManagers = buildTrustManagers();
okHttpClient = new OkHttpClient.Builder()
//设置连接超时时间
.connectTimeout(15, TimeUnit.SECONDS)
//写入超时时间
.writeTimeout(20, TimeUnit.SECONDS)
//从连接成功到响应的总时间
.readTimeout(20, TimeUnit.SECONDS)
//跳过ssl认证(https)
.sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0])
.hostnameVerifier((hostName, session) -> true)
.retryOnConnectionFailure(true)
// .proxy(proxy)//代理ip
//设置连接池 最大连接数量 , 持续存活的连接
.connectionPool(new ConnectionPool(50, 10, TimeUnit.MINUTES))
.build();
addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
}
}
}
}
/**
* 用于异步请求时,控制访问线程数,返回结果
*
*/
private static Semaphore getSemaphoreInstance() {
//只能1个线程同时访问
synchronized (OkHttpUtils.class) {
if (semaphore == null) {
semaphore = new Semaphore(0);
}
}
return semaphore;
}
/**
* 创建OkHttpUtils
*
*/
public static OkHttpUtils builder() {
return new OkHttpUtils();
}
/**
* 添加url
*
* @param url 地址
*/
public OkHttpUtils url(String url) {
this.url = url;
return this;
}
/**
* 添加参数
*
* @param key 参数名
* @param value 参数值
*/
public OkHttpUtils addParam(String key, String value) {
if (paramMap == null) {
paramMap = new LinkedHashMap<>(16);
}
paramMap.put(key, value);
return this;
}
/**
* 添加请求头
*
* @param key 参数名
* @param value 参数值
*/
public OkHttpUtils addHeader(String key, String value) {
if (headerMap == null) {
headerMap = new LinkedHashMap<>(16);
}
headerMap.put(key, value);
return this;
}
/**
* 初始化get方法
*
*/
public OkHttpUtils get() {
request = new Request.Builder().get();
StringBuilder urlBuilder = new StringBuilder(url);
if (paramMap != null) {
urlBuilder.append("?");
try {
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
urlBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8")).
append("=").
append(URLEncoder.encode(entry.getValue(), "utf-8")).
append("&");
}
} catch (Exception e) {
e.printStackTrace();
}
urlBuilder.deleteCharAt(urlBuilder.length() - 1);
}
request.url(urlBuilder.toString());
return this;
}
/**
* 初始化post方法
*
* @param isJsonPost true等于json的方式提交数据,类似postman里post方法的raw
* false等于普通的表单提交
*/
public OkHttpUtils post(boolean isJsonPost) {
RequestBody requestBody;
if (isJsonPost) {
String json = "";
if (paramMap != null) {
json = JSON.toJSONString(paramMap);
}
requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
} else {
FormBody.Builder formBody = new FormBody.Builder();
if (paramMap != null) {
paramMap.forEach(formBody::add);
}
requestBody = formBody.build();
}
request = new Request.Builder().post(requestBody).url(url);
return this;
}
public OkHttpUtils put() {
String json = "";
if (paramMap != null) {
json = JSON.toJSONString(paramMap);
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
request = new Request.Builder().put(requestBody).url(url);
return this;
}
public OkHttpUtils del() {
String json = "";
if (paramMap != null) {
json = JSON.toJSONString(paramMap);
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
request = new Request.Builder().delete(requestBody).url(url);
return this;
}
/**
* 同步请求
*
*/
public String sync() {
setHeader(request);
try {
Response response = okHttpClient.newCall(request.build()).execute();
assert response.body() != null;
return Objects.requireNonNull(response.body()).string();
} catch (IOException e) {
e.printStackTrace();
return "请求失败:" + e.getMessage();
}
}
/**
* 异步请求,有返回值
*/
public String async() {
StringBuilder buffer = new StringBuilder("");
setHeader(request);
okHttpClient.newCall(request.build()).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
buffer.append("请求出错:").append(e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
assert response.body() != null;
buffer.append(Objects.requireNonNull(response.body()).string());
getSemaphoreInstance().release();
}
});
try {
getSemaphoreInstance().acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
return buffer.toString();
}
/**
* 异步请求,带有接口回调
*
* @param callBack 回调
*/
public void async(ICallBack callBack) {
setHeader(request);
okHttpClient.newCall(request.build()).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
callBack.onFailure(call, e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
assert response.body() != null;
callBack.onSuccessful(call, Objects.requireNonNull(response.body()).string());
}
});
}
/**
* 为request添加请求头
*
* @param request 请求
*/
private void setHeader(Request.Builder request) {
if (headerMap != null) {
try {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 生成安全套接字工厂,用于https请求的证书跳过
*
* @return SSLSocketFactory
*/
private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return ssfFactory;
}
private static TrustManager[] buildTrustManagers() {
return new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
};
}
/**
* 自定义一个接口回调 - 发送异步请求时可以实现这个接口
*/
public interface ICallBack {
/**
* 接口正常调用返回的内容
*
* @param call 回调
* @param data 返回数据
*/
void onSuccessful(Call call, String data);
/**
* 接口错误返回的内容
*
* @param call 回调
* @param errorMsg 错误信息
*/
void onFailure(Call call, String errorMsg);
}
}
测试
@SpringBootTest
class OkhttpTestApplicationTests {
@Test
public void testOkhttpGet() {
String res = OkHttpUtils.builder()
.url("http://localhost:8080/user/login")
.addParam("name", "li").addParam("password", "123456")
.get()
.sync();
System.out.println(res);
}
@Test
public void testOkhttpPost() {
String res = OkHttpUtils.builder()
.url("http://localhost:8080/user/register")
.addParam("name", "li").addParam("password", "123456")
.post(true)
.sync();
System.out.println(res);
}
@Test
public void testOkhttpAsync() {
OkHttpUtils.builder()
.url("http://localhost:8080/user/register")
.addParam("name", "li").addParam("password", "123456")
.post(true)
.async(new AsyncHttpServiceImpl());
}
//回调实现类
public class AsyncHttpServiceImpl implements OkHttpUtils.ICallBack {
@Override
public void onSuccessful(Call call, String data) {
// 接口正常返回的内容
System.out.println("onSuccessful" + data);
}
@Override
public void onFailure(Call call, String errorMsg) {
//接口错误返回的内容
System.out.println("onFailure" + errorMsg);
}
}
}
2、Semaphore
Semaphore当前在多线程环境下被广泛使用,信号量是个很重要的概念,在进程控制方面都有应用。Java 并发库 的Semaphore 可以很轻松完成信号量控制,Semaphore可以控制某个资源可被同时访问的个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可
代码实践
通过例子了解Semaphore的具体使用:
停车场有五个车位,有十辆车需要进入停车场停车,此时需要保证停车场最多的时候只能有五辆车进入,出去一辆才能进来一辆
代码实现:
public static void main(String[] args) {
// 停车场车位数量
Semaphore semaphore = new Semaphore(5);
for (int i = 1; i <= 10; i++) {
Thread thread = new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "进入停车场");
TimeUnit.SECONDS.sleep(new Random().nextInt(10));
System.out.println(Thread.currentThread().getName() + "驶离停车场");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
semaphore.release();
}
}, i + "号车");
thread.start();
}
}
运行结果
1号车进入停车场
4号车进入停车场
3号车进入停车场
2号车进入停车场
5号车进入停车场
1号车驶离停车场
7号车进入停车场
4号车驶离停车场
6号车进入停车场
5号车驶离停车场
8号车进入停车场
3号车驶离停车场
9号车进入停车场
9号车驶离停车场
10号车进入停车场
2号车驶离停车场
6号车驶离停车场
7号车驶离停车场
8号车驶离停车场
10号车驶离停车场
Process finished with exit code 0