<dependency>
<groupId>io.freefair.okhttp-spring-boot</groupId>
<artifactId>okhttp3-spring-boot-starter</artifactId>
<version>2.4.0-rc1</version>
</dependency>
package com.ysh.config;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
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 OkHttpConfiguration {
@Bean
public X509TrustManager x509TrustManager(){
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) 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 e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
/**
* Create a new connection pool with tuning parameters appropriate for a single-user application.
* The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
*/
@Bean
public ConnectionPool pool() {
return new ConnectionPool(200, 5, TimeUnit.MINUTES);
}
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory(), x509TrustManager())
.retryOnConnectionFailure(false)//是否开启缓存
.connectionPool(pool())//连接池
.connectTimeout(10L, TimeUnit.SECONDS)
.readTimeout(10L, TimeUnit.SECONDS)
.build();
}
}
package com.ysh.utils;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
@Component
public class OkHttpUtil {
private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
@Resource
private OkHttpClient okHttpClient;
/**
* get
*
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return
*/
public String get(String url, Map<String, String> queries) {
String responseBody = "";
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = queries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry<String, String>) iterator.next();
if (firstFlag) {
sb.append("?" + entry.getKey() + "=" + entry.getValue());
firstFlag = false;
} else {
sb.append("&" + entry.getKey() + "=" + entry.getValue());
}
}
}
Request request = new Request
.Builder()
.url(sb.toString())
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (status == 200) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp put error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* post
*
* @param url 请求的url
* @param params post form 提交的参数
* @return
*/
public String post(String url, Map<String, String> params) {
String responseBody = "";
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();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (status == 200) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* post 上传文件
*
* @param url
* @param params
* @param fileType
* @return
*/
public String postFile(String url, Map<String, Object> params, String fileType) {
String responseBody = "";
MultipartBody.Builder builder = new MultipartBody.Builder();
//添加参数
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
if (params.get(key) instanceof File) {
File file = (File) params.get(key);
builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(fileType), file));
continue;
}
builder.addFormDataPart(key, params.get(key).toString());
}
}
Request request = new Request
.Builder()
.url(url)
.post(builder.build())
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (status == 200) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp postFile error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
}
就是启动这个项目
package com.ysh;
import com.ysh.entity.User;
import com.ysh.service.UserService;
import com.ysh.utils.OkHttpUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@SpringBootTest
class SpringbootMybatisApplicationTests {
@Resource
private OkHttpUtil okHttpUtil;
@Test
void contextLoads() {
Map<String,String> map = new HashMap<>();
map.put("name","lixusheng");
map.put("sex","1");
map.put("age","18");
String post = okHttpUtil.post("http://localhost:8080/add", map);
System.out.println(post);
}
}
成功
原文:https://www.cnblogs.com/lxs1204/p/14276072.html