Compare commits
3 Commits
d110213b14
...
a41d25685f
| Author | SHA1 | Date | |
|---|---|---|---|
| a41d25685f | |||
| 88b023ca00 | |||
| 0b5ab3ccca |
6
pom.xml
6
pom.xml
@ -82,12 +82,14 @@
|
||||
<version>${fastjson.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
|
||||
@ -0,0 +1,65 @@
|
||||
package top.krcia.common.component.deepseek;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import top.krcia.common.component.deepseek.bean.ChatRoomRecord;
|
||||
import top.krcia.common.component.deepseek.bean.DeepSeekParam;
|
||||
import top.krcia.common.request.WebRequest;
|
||||
import top.krcia.common.request.enums.RequestType;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class Deepseek {
|
||||
private final String URL = "https://api.deepseek.com/chat/completions";
|
||||
private DeepSeekParam deepSeekParam = null;
|
||||
private String apiKey;
|
||||
|
||||
private Deepseek(DeepSeekParam deepSeekParam, String apiKey) {
|
||||
this.deepSeekParam = deepSeekParam;
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
public static Deepseek build(String apiKey, String model, String robotTemplate, int temperature) {
|
||||
return new Deepseek(new DeepSeekParam(model, robotTemplate, temperature), apiKey);
|
||||
}
|
||||
|
||||
public String sendChat(String systemPrompt, List<ChatRoomRecord> message) {
|
||||
deepSeekParam.setSystemPrompt(systemPrompt);
|
||||
deepSeekParam.setContent(message);
|
||||
|
||||
try {
|
||||
String result = WebRequest.Create(new URI(URL))
|
||||
.setBody(JSON.parseObject(JSON.toJSONString(deepSeekParam)))
|
||||
.setHeader(Map.of("Authorization", "Bearer ".concat(apiKey)))
|
||||
.setRequestType(RequestType.POST)
|
||||
.execute();
|
||||
return JSON.parseObject(result)
|
||||
.getJSONArray("choices")
|
||||
.getJSONObject(0)
|
||||
.getJSONObject("message")
|
||||
.getString("content");
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String sendEngine(String message) {
|
||||
deepSeekParam.setContent(message);
|
||||
try {
|
||||
String result = WebRequest.Create(new URI(URL))
|
||||
.setBody(JSON.parseObject(JSON.toJSONString(deepSeekParam)))
|
||||
.setHeader(Map.of("Authorization", "Bearer ".concat(apiKey)))
|
||||
.setRequestType(RequestType.POST)
|
||||
.execute();
|
||||
return JSON.parseObject(result)
|
||||
.getJSONArray("choices")
|
||||
.getJSONObject(0)
|
||||
.getJSONObject("message")
|
||||
.getString("content");
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
package top.krcia.common.component.deepseek.bean;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.extension.activerecord.Model;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* (ChatRoomRecord)表实体类
|
||||
*
|
||||
* @author admin
|
||||
* @since 2025-09-11 11:14:00
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
@Data
|
||||
public class ChatRoomRecord extends Model<ChatRoomRecord> {
|
||||
@TableId
|
||||
//消息ID
|
||||
private String messageId;
|
||||
//聊天时间
|
||||
private Date chatDate;
|
||||
//消息所属者(0:机器人|1用户)
|
||||
private Integer from;
|
||||
//消息内容
|
||||
private String message;
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,64 @@
|
||||
package top.krcia.common.component.deepseek.bean;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class DeepSeekParam {
|
||||
private String model;
|
||||
private List<MessagesDTO> messages;
|
||||
private final Boolean stream = false;
|
||||
private double temperature;
|
||||
|
||||
public DeepSeekParam(String model, String robotTemplate, double temperature) {
|
||||
messages = new ArrayList<>();
|
||||
MessagesDTO messagesDTO = new MessagesDTO();
|
||||
messagesDTO.setRole("system");
|
||||
messagesDTO.setContent(robotTemplate);
|
||||
messages.add(messagesDTO);
|
||||
this.model = model;
|
||||
this.temperature = temperature;
|
||||
}
|
||||
|
||||
public void setSystemPrompt(String systemPrompt) {
|
||||
MessagesDTO messagesDTO = new MessagesDTO();
|
||||
messagesDTO.setRole("system");
|
||||
messagesDTO.setContent(systemPrompt);
|
||||
messages.add(messagesDTO);
|
||||
}
|
||||
|
||||
public void setContent(List<ChatRoomRecord> message) {
|
||||
List<MessagesDTO> messagesDTOS = new ArrayList<>();
|
||||
for (ChatRoomRecord crr : message) {
|
||||
MessagesDTO messagesDTO = new MessagesDTO(crr.getFrom() == 0 ? "assistant" : "user",crr.getMessage());
|
||||
messagesDTOS.add(messagesDTO);
|
||||
}
|
||||
messages.addAll(messagesDTOS);
|
||||
}
|
||||
public void setContent(String message) {
|
||||
messages.add(new MessagesDTO("user",message));
|
||||
}
|
||||
public void setContent(int from,String message) {
|
||||
List<MessagesDTO> messagesDTOS = new ArrayList<>();
|
||||
MessagesDTO messagesDTO = new MessagesDTO(from== 0 ? "assistant" : "user", message);
|
||||
messagesDTOS.add(messagesDTO);
|
||||
messages.addAll(messagesDTOS);
|
||||
}
|
||||
|
||||
|
||||
@Data
|
||||
public static class MessagesDTO {
|
||||
private String role;
|
||||
private String content;
|
||||
|
||||
public MessagesDTO(String role, String content) {
|
||||
this.role = role;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public MessagesDTO() {
|
||||
}
|
||||
}
|
||||
}
|
||||
17
src/main/java/top/krcia/common/config/MyBatisPlusConfig.java
Normal file
17
src/main/java/top/krcia/common/config/MyBatisPlusConfig.java
Normal file
@ -0,0 +1,17 @@
|
||||
package top.krcia.common.config;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
@Configuration
|
||||
@EnableScheduling
|
||||
public class MyBatisPlusConfig {
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
|
||||
return interceptor;
|
||||
}
|
||||
}
|
||||
389
src/main/java/top/krcia/common/request/RequestHelper.java
Normal file
389
src/main/java/top/krcia/common/request/RequestHelper.java
Normal file
@ -0,0 +1,389 @@
|
||||
package top.krcia.common.request;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import io.micrometer.common.util.StringUtils;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.CookieStore;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.config.AuthSchemes;
|
||||
import org.apache.http.client.config.CookieSpecs;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.HttpDelete;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpPut;
|
||||
import org.apache.http.config.Registry;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class RequestHelper {
|
||||
|
||||
/**
|
||||
* get
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param headers
|
||||
* @param queryMap
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpEntity get(String host, String path, MediaType mediaType,
|
||||
Map<String, String> headers,
|
||||
Map<String, Object> queryMap, CookieStore cookies, int timeOut) throws IOException {
|
||||
HttpClient httpClient = wrapClient(host, path, cookies);
|
||||
HttpGet request = null;
|
||||
try {
|
||||
request = new HttpGet(buildUrl(host, path, queryMap));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
request.setHeader("Content-Type", mediaType.getType() + "/" + mediaType.getSubtype());
|
||||
try {
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
|
||||
request.setConfig(RequestConfig.custom().setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut).setSocketTimeout(timeOut).build());
|
||||
HttpResponse response = null;
|
||||
response = httpClient.execute(request);
|
||||
return response.getEntity();
|
||||
}
|
||||
|
||||
/**
|
||||
* post form
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param headers
|
||||
* @param queryMap
|
||||
* @param bodyMap
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpEntity post(String host, String path, MediaType mediaType,
|
||||
Map<String, String> headers,
|
||||
Map<String, Object> queryMap,
|
||||
Map<String, Object> bodyMap, CookieStore cookies, int timeOut) throws IOException {
|
||||
HttpClient httpClient = wrapClient(host, path, cookies);
|
||||
HttpPost request = null;
|
||||
try {
|
||||
request = new HttpPost(buildUrl(host, path, queryMap));
|
||||
request.setConfig(RequestConfig.custom().setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut).setSocketTimeout(timeOut).build());
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
request.setHeader("Content-Type", mediaType.getType() + "/" + mediaType.getSubtype());
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
if (bodyMap != null && bodyMap.size() > 0) {
|
||||
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
|
||||
|
||||
for (String key : bodyMap.keySet()) {
|
||||
nameValuePairList.add(new BasicNameValuePair(key, bodyMap.get(key).toString()));
|
||||
}
|
||||
UrlEncodedFormEntity formEntity = null;
|
||||
try {
|
||||
formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
|
||||
request.setEntity(formEntity);
|
||||
}
|
||||
HttpResponse response = httpClient.execute(request);return response.getEntity();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Post String
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param headers
|
||||
* @param queryMap
|
||||
* @param body
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpEntity post(String host, String path, MediaType mediaType,
|
||||
Map<String, String> headers,
|
||||
Map<String, Object> queryMap,
|
||||
String body, CookieStore cookies, int timeOut) throws IOException {
|
||||
HttpClient httpClient = wrapClient(host, path, cookies);
|
||||
HttpPost request = null;
|
||||
try {
|
||||
request = new HttpPost(buildUrl(host, path, queryMap));
|
||||
|
||||
request.setConfig(RequestConfig.custom().setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut).setSocketTimeout(timeOut).build());
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
request.setHeader("Content-Type", mediaType.getType() + "/" + mediaType.getSubtype());
|
||||
try {
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
if (StringUtils.isNotBlank(body)) {
|
||||
request.setEntity(new StringEntity(body, "utf-8"));
|
||||
}
|
||||
HttpResponse response = httpClient.execute(request);return response.getEntity();
|
||||
}
|
||||
|
||||
/**
|
||||
* Post String
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param headers
|
||||
* @param queryMap
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpEntity post(String host, String path, MediaType mediaType,
|
||||
Map<String, String> headers,
|
||||
Map<String, Object> queryMap, CookieStore cookies, int timeOut) throws IOException {
|
||||
HttpClient httpClient = wrapClient(host, path, cookies);
|
||||
HttpPost request = null;
|
||||
try {
|
||||
request = new HttpPost(buildUrl(host, path, queryMap));
|
||||
|
||||
request.setConfig(RequestConfig.custom().setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut).setSocketTimeout(timeOut).build());
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
request.setHeader("Content-Type", mediaType.getType() + "/" + mediaType.getSubtype());
|
||||
try {
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
HttpResponse response = httpClient.execute(request);return response.getEntity();
|
||||
}
|
||||
|
||||
/**
|
||||
* Put String
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param headers
|
||||
* @param queryMap
|
||||
* @param body
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpEntity put(String host, String path, MediaType mediaType,
|
||||
Map<String, String> headers,
|
||||
Map<String, Object> queryMap,
|
||||
String body, CookieStore cookies, int timeOut)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host, path, cookies);
|
||||
HttpPut request = new HttpPut(buildUrl(host, path, queryMap));
|
||||
request.setConfig(RequestConfig.custom().setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut).setSocketTimeout(timeOut).build());
|
||||
request.setHeader("Content-Type", mediaType.getType() + "/" + mediaType.getSubtype());
|
||||
try {
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
;
|
||||
if (StringUtils.isNotBlank(body)) {
|
||||
request.setEntity(new StringEntity(body, "utf-8"));
|
||||
}
|
||||
HttpResponse response = httpClient.execute(request);return response.getEntity();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param headers
|
||||
* @param queryMap
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpEntity delete(String host, String path, MediaType mediaType,
|
||||
Map<String, String> headers,
|
||||
Map<String, Object> queryMap, CookieStore cookies, int timeOut)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host, path, cookies);
|
||||
HttpDelete request = new HttpDelete(buildUrl(host, path, queryMap));
|
||||
request.setConfig(RequestConfig.custom().setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut).setSocketTimeout(timeOut).build());
|
||||
request.setHeader("Content-Type", mediaType.getType() + "/" + mediaType.getSubtype());
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
HttpResponse response = httpClient.execute(request);return response.getEntity();
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建请求的 url
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param queryMap
|
||||
* @return
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
private static String buildUrl(String host, String path, Map<String, Object> queryMap) throws UnsupportedEncodingException {
|
||||
StringBuilder sbUrl = new StringBuilder();
|
||||
if (!StringUtils.isBlank(host)) {
|
||||
sbUrl.append(host);
|
||||
}
|
||||
if (!StringUtils.isBlank(path)) {
|
||||
sbUrl.append(path);
|
||||
}
|
||||
if (null != queryMap) {
|
||||
StringBuilder sbQuery = new StringBuilder();
|
||||
for (Map.Entry<String, Object> query : queryMap.entrySet()) {
|
||||
if (0 < sbQuery.length()) {
|
||||
sbQuery.append("&");
|
||||
}
|
||||
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue().toString())) {
|
||||
sbQuery.append(query.getValue());
|
||||
}
|
||||
if (!StringUtils.isBlank(query.getKey())) {
|
||||
sbQuery.append(query.getKey());
|
||||
if (!StringUtils.isBlank(query.getValue().toString())) {
|
||||
sbQuery.append("=");
|
||||
sbQuery.append(URLEncoder.encode(query.getValue().toString(), "utf-8"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (0 < sbQuery.length()) {
|
||||
sbUrl.append("?").append(sbQuery);
|
||||
}
|
||||
}
|
||||
return sbUrl.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 HttpClient
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @return
|
||||
*/
|
||||
private static HttpClient wrapClient(String host, String path, CookieStore cookies) {
|
||||
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
|
||||
if (cookies != null) {
|
||||
httpClientBuilder.setDefaultCookieStore(cookies);
|
||||
}
|
||||
HttpClient httpClient = httpClientBuilder.build();
|
||||
if (host != null && host.startsWith("https://")) {
|
||||
return sslClient();
|
||||
} else if (StringUtils.isBlank(host) && path != null && path.startsWith("https://")) {
|
||||
return sslClient();
|
||||
}
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在调用SSL之前需要重写验证方法,取消检测SSL
|
||||
* 创建ConnectionManager,添加Connection配置信息
|
||||
*
|
||||
* @return HttpClient 支持https
|
||||
*/
|
||||
private static HttpClient sslClient() {
|
||||
try {
|
||||
// 在调用SSL之前需要重写验证方法,取消检测SSL
|
||||
X509TrustManager trustManager = new X509TrustManager() {
|
||||
@Override
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] xcs, String str) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] xcs, String str) {
|
||||
}
|
||||
};
|
||||
SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
|
||||
ctx.init(null, new TrustManager[]{trustManager}, null);
|
||||
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
|
||||
// 创建Registry
|
||||
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
|
||||
.setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
|
||||
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
|
||||
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", PlainConnectionSocketFactory.INSTANCE)
|
||||
.register("https", socketFactory).build();
|
||||
// 创建ConnectionManager,添加Connection配置信息
|
||||
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
|
||||
CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
|
||||
.setDefaultRequestConfig(requestConfig).build();
|
||||
return closeableHttpClient;
|
||||
} catch (KeyManagementException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将结果转换成JSONObject
|
||||
*
|
||||
* @param httpResponse
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static JSONObject parseJson(HttpResponse httpResponse) throws IOException {
|
||||
return JSON.parseObject(parseString(httpResponse));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将结果转换成 String
|
||||
*
|
||||
* @param httpResponse
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String parseString(HttpResponse httpResponse) throws IOException {
|
||||
HttpEntity entity = httpResponse.getEntity();
|
||||
String resp = EntityUtils.toString(entity, "UTF-8");
|
||||
EntityUtils.consume(entity);
|
||||
return resp;
|
||||
}
|
||||
}
|
||||
162
src/main/java/top/krcia/common/request/WebRequest.java
Normal file
162
src/main/java/top/krcia/common/request/WebRequest.java
Normal file
@ -0,0 +1,162 @@
|
||||
package top.krcia.common.request;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.CookieStore;
|
||||
import org.apache.http.impl.client.BasicCookieStore;
|
||||
import org.apache.http.impl.cookie.BasicClientCookie;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.springframework.http.MediaType;
|
||||
import top.krcia.common.request.bean.HttpFile;
|
||||
import top.krcia.common.request.enums.RequestType;
|
||||
import top.krcia.common.request.interfaces.WebRequestOption;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
|
||||
public class WebRequest implements WebRequestOption {
|
||||
private Map<String, String> headers;
|
||||
private Map<String, Object> params;
|
||||
private String body;
|
||||
private Map<String, Object> bodyForm;
|
||||
private RequestType requestType = RequestType.GET;
|
||||
private MediaType mediaType = MediaType.APPLICATION_JSON;
|
||||
private int timeout = -1;
|
||||
|
||||
private CookieStore cookies = new BasicCookieStore();
|
||||
|
||||
private URI url;
|
||||
|
||||
@Override
|
||||
public WebRequest setHeader(Map<String, String> headers) {
|
||||
this.headers = headers;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebRequest setParam(Map<String, Object> params) {
|
||||
this.params = params;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebRequest setBody(JSONObject body) {
|
||||
this.body = body.toJSONString();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> WebRequest setBody(T body) {
|
||||
this.body = JSON.toJSONString(body);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebRequest setBodyForm(Map<String, Object> bodyForm) {
|
||||
this.bodyForm = bodyForm;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebRequest setCookie(Map<String, String> cookies) {
|
||||
for (var item : cookies.keySet()) {
|
||||
BasicClientCookie cookie = new BasicClientCookie(item, cookies.get(item));
|
||||
cookie.setDomain(url.getHost());
|
||||
cookie.setPath("/");
|
||||
this.cookies.addCookie(cookie);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebRequest setRequestType(RequestType requestType) {
|
||||
this.requestType = requestType;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebRequest setTimeOut(int timeout) {
|
||||
this.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebRequest setContentType(MediaType mediaType) {
|
||||
this.mediaType = mediaType;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String execute() throws Exception {
|
||||
switch (requestType) {
|
||||
case GET -> {
|
||||
return EntityUtils.toString(RequestHelper.get(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, cookies, timeout));
|
||||
}
|
||||
case POST -> {
|
||||
if (bodyForm != null) {
|
||||
return EntityUtils.toString(RequestHelper.post(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, bodyForm, cookies, timeout));
|
||||
} else if (body != null) {
|
||||
return EntityUtils.toString(RequestHelper.post(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, body, cookies, timeout));
|
||||
} else {
|
||||
return EntityUtils.toString(RequestHelper.post(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, cookies, timeout));
|
||||
}
|
||||
}
|
||||
case PUT -> {
|
||||
return EntityUtils.toString(RequestHelper.put(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, body, cookies, timeout));
|
||||
}
|
||||
case DELETE -> {
|
||||
return EntityUtils.toString(RequestHelper.delete(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, cookies, timeout));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpFile executeFile() throws Exception {
|
||||
HttpEntity entity=null;
|
||||
switch (requestType) {
|
||||
case GET -> {
|
||||
entity= RequestHelper.get(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, cookies, timeout);
|
||||
}
|
||||
case POST -> {
|
||||
if (bodyForm != null) {
|
||||
entity= RequestHelper.post(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, bodyForm, cookies, timeout);
|
||||
} else if (body != null) {
|
||||
entity= RequestHelper.post(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, body, cookies, timeout);
|
||||
} else {
|
||||
entity= RequestHelper.post(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, cookies, timeout);
|
||||
}
|
||||
}
|
||||
case PUT -> {
|
||||
entity= RequestHelper.put(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, body, cookies, timeout);
|
||||
}
|
||||
case DELETE -> {
|
||||
entity= RequestHelper.delete(url.getScheme() + "://" + url.getHost() + ":" + url.getPort(), url.getPath(), mediaType, headers, params, cookies, timeout);
|
||||
}
|
||||
}
|
||||
if (entity != null) {
|
||||
String contentType = entity.getContentType() != null ? entity.getContentType().getValue() : "application/octet-stream";
|
||||
try (InputStream inputStream = entity.getContent();
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
|
||||
byte[] tmp = new byte[8192];
|
||||
int len;
|
||||
while ((len = inputStream.read(tmp)) != -1) {
|
||||
bos.write(tmp, 0, len);
|
||||
}
|
||||
return new HttpFile(bos, contentType);
|
||||
}
|
||||
}
|
||||
return new HttpFile(new ByteArrayOutputStream(), "application/octet-stream");
|
||||
}
|
||||
|
||||
public WebRequest(URI url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public static WebRequest Create(URI url) {
|
||||
return new WebRequest(url);
|
||||
}
|
||||
}
|
||||
75
src/main/java/top/krcia/common/request/bean/HttpFile.java
Normal file
75
src/main/java/top/krcia/common/request/bean/HttpFile.java
Normal file
@ -0,0 +1,75 @@
|
||||
package top.krcia.common.request.bean;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpFile {
|
||||
private final ByteArrayOutputStream buffer;
|
||||
public final long size;
|
||||
public final FileFormat format;
|
||||
private final String version="v 0.1";
|
||||
|
||||
public HttpFile(ByteArrayOutputStream buffer, String contentType) {
|
||||
this.buffer = buffer;
|
||||
this.size = buffer.size();
|
||||
this.format = detectFormat(contentType);
|
||||
}
|
||||
|
||||
public void saveAs(Path path) throws IOException {
|
||||
try (FileOutputStream fos = new FileOutputStream(path.toString())) {
|
||||
buffer.writeTo(fos);
|
||||
}
|
||||
}
|
||||
|
||||
// 获取 InputStream
|
||||
public InputStream asStream() {
|
||||
return new ByteArrayInputStream(buffer.toByteArray());
|
||||
}
|
||||
|
||||
public byte[] asBytes() {
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
|
||||
private FileFormat detectFormat(String contentType) {
|
||||
if (contentType == null) {
|
||||
return FileFormat.UNKNOWN;
|
||||
}
|
||||
if (contentType.contains("mpeg")) {
|
||||
return FileFormat.MP3;
|
||||
} else if (contentType.contains("mp4")) {
|
||||
return FileFormat.MP4;
|
||||
} else if (contentType.contains("png")) {
|
||||
return FileFormat.PNG;
|
||||
} else if (contentType.contains("jpeg") || contentType.contains("jpg")) {
|
||||
return FileFormat.JPG;
|
||||
} else if (contentType.contains("plain")) {
|
||||
return FileFormat.TXT;
|
||||
} else if (contentType.contains("pdf")) {
|
||||
return FileFormat.PDF;
|
||||
}
|
||||
return FileFormat.UNKNOWN;
|
||||
}
|
||||
|
||||
public enum FileFormat {
|
||||
MP3("mp3"), MP4("mp4"), PNG("png"), JPG("jpg"), TXT("txt"), PDF("pdf"), UNKNOWN("bin");
|
||||
private final String value;
|
||||
|
||||
FileFormat(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
Map<String,Object> data = new HashMap<>();
|
||||
data.put("size",size);
|
||||
data.put("format",format.value);
|
||||
data.put("version",version);
|
||||
return JSON.toJSONString(data);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,5 @@
|
||||
package top.krcia.common.request.enums;
|
||||
|
||||
public enum RequestType {
|
||||
GET,POST,PUT,DELETE
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
package top.krcia.common.request.interfaces;
|
||||
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.springframework.http.MediaType;
|
||||
import top.krcia.common.request.WebRequest;
|
||||
import top.krcia.common.request.bean.HttpFile;
|
||||
import top.krcia.common.request.enums.RequestType;
|
||||
|
||||
import java.util.Map;
|
||||
public interface WebRequestOption {
|
||||
WebRequest setHeader(Map<String, String> headers);
|
||||
WebRequest setParam(Map<String, Object> params);
|
||||
WebRequest setBody(JSONObject body);
|
||||
<T> WebRequest setBody(T body);
|
||||
WebRequest setBodyForm(Map<String, Object> bodyForm);
|
||||
WebRequest setCookie(Map<String, String> cookie);
|
||||
WebRequest setRequestType(RequestType requestType);
|
||||
WebRequest setTimeOut(int timeout);
|
||||
WebRequest setContentType(MediaType mediaType);
|
||||
String execute() throws Exception;
|
||||
HttpFile executeFile() throws Exception;
|
||||
}
|
||||
8
src/main/resources/application-dev.properties
Normal file
8
src/main/resources/application-dev.properties
Normal file
@ -0,0 +1,8 @@
|
||||
#???
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.url=jdbc:mysql://krcia.top:63306/elysia?serverTimezone=Asia/Shanghai
|
||||
spring.datasource.username=root
|
||||
spring.datasource.password=xiong990416.
|
||||
#????
|
||||
spring.servlet.multipart.max-file-size=10MB
|
||||
spring.servlet.multipart.max-request-size=10MB
|
||||
0
src/main/resources/application-res.properties
Normal file
0
src/main/resources/application-res.properties
Normal file
@ -1 +1,5 @@
|
||||
spring.application.name=elysia-server
|
||||
server.port=4560
|
||||
spring.profiles.active=dev
|
||||
#????
|
||||
server.max-http-request-header-size=16KB
|
||||
20
src/main/resources/smart-doc.json
Normal file
20
src/main/resources/smart-doc.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"outPath": "./src/main/resources/static/doc",
|
||||
"serverUrl": "/api",
|
||||
"serverEnv": "http://{{server}}",
|
||||
"allInOne": true,
|
||||
"coverOld": true,
|
||||
"createDebugPage": true,
|
||||
"showAuthor": "true",
|
||||
"allInOneDocFileName": "index.html",
|
||||
"requestHeaders": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"value": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCJ9.eyJpZCI6MTAwMDAwfQ.yBaS2nSUJoD2kbhj3lXnHvkmc-qwJF_5djhQf_2A069j9HzYVmUObXcDwaAhHQf-",
|
||||
"desc": "鉴权信息",
|
||||
"required": true,
|
||||
"excludePathPatterns": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user