1.导入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
我的实体类需要使用@NotEmpty
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.application.properties
server.port=8081
ok.http.connect-timeout=100
ok.http.read-timeout=100
ok.http.write-timeout=100
ok.http.max-idle-connections=100
ok.http.keep-alive-duration=100
3.config类
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
@Configuration
public class OkHttpConfig {
@Value("${ok.http.connect-timeout}")
private Integer connectTimeout;
@Value("${ok.http.read-timeout}")
private Integer readTimeout;
@Value("${ok.http.write-timeout}")
private Integer writeTimeout;
@Value("${ok.http.max-idle-connections}")
private Integer maxIdleConnections;
@Value("${ok.http.keep-alive-duration}")
private Long keepAliveDuration;
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory(), x509TrustManager())
// 是否开启缓存
.retryOnConnectionFailure(false)
.connectionPool(pool())
.connectTimeout(connectTimeout, TimeUnit.SECONDS)
.readTimeout(readTimeout, TimeUnit.SECONDS)
.writeTimeout(writeTimeout,TimeUnit.SECONDS)
.hostnameVerifier((hostname, session) -> true)
.build();
}
@Bean
public X509TrustManager x509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
}
@Bean
public SSLSocketFactory sslSocketFactory() {
try {
// 信任任何链接
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
return null;
}
@Bean
public ConnectionPool pool() {
return new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
}
}
4.utils类
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
@Slf4j
@Component
public class OkHttpUtils {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");
@Autowired
private OkHttpClient okHttpClient;
/**
* get 请求
* @param url 请求url地址
* @return string
* */
public String doGet(String url) {
return doGet(url, null, null);
}
/**
* get 请求
* @param url 请求url地址
* @param params 请求参数 map
* @return string
* */
public String doGet(String url, Map<String, String> params) {
return doGet(url, params, null);
}
/**
* get 请求
* @param url 请求url地址
* @param headers 请求头字段 {k1, v1 k2, v2, ...}
* @return string
* */
public String doGet(String url, String[] headers) {
return doGet(url, null, headers);
}
/**
* get 请求
* @param url 请求url地址
* @param params 请求参数 map
* @param headers 请求头字段 {k1, v1 k2, v2, ...}
* @return string
* */
public String doGet(String url, Map<String, String> params, String[] headers) {
StringBuilder sb = new StringBuilder(url);
if (params != null && params.keySet().size() > 0) {
boolean firstFlag = true;
for (String key : params.keySet()) {
if (firstFlag) {
sb.append("?").append(key).append("=").append(params.get(key));
firstFlag = false;
} else {
sb.append("&").append(key).append("=").append(params.get(key));
}
}
}
Request.Builder builder = new Request.Builder();
if (headers != null && headers.length > 0) {
if (headers.length % 2 == 0) {
for (int i = 0; i < headers.length; i = i + 2) {
builder.addHeader(headers[i], headers[i + 1]);
}
} else {
log.warn("headers's length[{}] is error.", headers.length);
}
}
Request request = builder.url(sb.toString()).build();
log.info("do get request and url[{}]", sb.toString());
return execute(request);
}
/**
* post 请求
* @param url 请求url地址
* @param params 请求参数 map
* @return string
*/
public String doPost(String url, Map<String, String> params) {
FormBody.Builder builder = new FormBody.Builder();
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}
}
Request request = new Request.Builder().url(url).post(builder.build()).build();
log.info("do post request and url[{}]", url);
return execute(request);
}
/**
* post 请求, 请求数据为 json 的字符串
* @param url 请求url地址
* @param json 请求数据, json 字符串
* @return string
*/
public String doPostJson(String url, String json) {
log.info("do post request and url[{}]", url);
return exectePost(url, json, JSON);
}
/**
* post 请求, 请求数据为 xml 的字符串
* @param url 请求url地址
* @param xml 请求数据, xml 字符串
* @return string
*/
public String doPostXml(String url, String xml) {
log.info("do post request and url[{}]", url);
return exectePost(url, xml, XML);
}
private String exectePost(String url, String data, MediaType contentType) {
RequestBody requestBody = RequestBody.create(contentType, data);
Request request = new Request.Builder().url(url).post(requestBody).build();
return execute(request);
}
private String execute(Request request) {
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return "";
}
}
5.连接Nifi测试
<dependency>
<groupId>org.apache.nifi</groupId>
<artifactId>nifi-api</artifactId>
<version>1.15.0</version>
<scope>provided</scope>
</dependency>
nifi.url=https://10xxxxxx9:18080/nifi-api
nifi.user=xxxxx
nifi.password=xxxxx
@Component
public class ETLServer {
@Value("${nifi.url}")
private String url;
@Value("${nifi.user}")
private String username;
@Value("${nifi.password}")
private String password;
@Autowired
private OkHttpUtils okHttpUtils;
public String getToken(){
String requestUrl = url+"/access/token";
Map<String,String> logMessageMap = new HashMap<>();
logMessageMap.put("username",username);
logMessageMap.put("password",password);
return okHttpUtils.doPost(requestUrl, logMessageMap);
}
public CommonEntity getCommonEntity(){
CommonEntity commonEntity = new CommonEntity();
commonEntity.setUrl(url);
commonEntity.setAccessToken(getToken());
return commonEntity;
}
}
@Data
public class CommonEntity {
@NotEmpty(message = "url must not be empty")
private String url;
@NotEmpty(message = "accessToken must not be empty")
private String accessToken;
}
2021-12-23:又发现了Forest框架,更简单的封装
Forest Http使用分享: https://blog.csdn.net/weixin_43916074/article/details/122078318.