├── src └── main │ ├── java │ └── com │ │ └── openapi │ │ ├── Dao │ │ ├── ChatHistMapper.java │ │ ├── InviteCodeMapper.java │ │ ├── CodeUserQuotaMapper.java │ │ └── CodeUserMapper.java │ │ ├── Basic │ │ ├── Return_Fields.java │ │ ├── SystemConstant.java │ │ ├── BasicCode.java │ │ ├── JsonConvert.java │ │ └── Return.java │ │ ├── Model │ │ ├── CodeUserQuota.java │ │ ├── ChatHist.java │ │ ├── InviteCode.java │ │ └── CodeUser.java │ │ ├── App.java │ │ ├── tools │ │ ├── OkHttpClientUtil │ │ │ ├── SSLUtil.java │ │ │ ├── SSLSocketClient.java │ │ │ └── OkHttpTools.java │ │ ├── CommonUtils.java │ │ ├── ThreadLocalUtil.java │ │ ├── XmlToJson.java │ │ └── NativePath.java │ │ ├── Database │ │ └── TgDataSourceConfig.java │ │ ├── Controller │ │ └── AICodeController.java │ │ └── Service │ │ └── CodeUserService.java │ └── resources │ ├── conf │ └── args.properties │ ├── log4j2.xml │ ├── mybatis-config.xml │ ├── db_init.sql │ └── mapping │ ├── ChatHistMapper.xml │ ├── InviteCodeMapper.xml │ ├── CodeUserQuotaMapper.xml │ └── CodeUserMapper.xml ├── README.md └── pom.xml /src/main/java/com/openapi/Dao/ChatHistMapper.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Dao; 2 | 3 | import com.openapi.Model.ChatHist; 4 | 5 | 6 | public interface ChatHistMapper { 7 | 8 | int insert(ChatHist record); 9 | 10 | 11 | 12 | 13 | } -------------------------------------------------------------------------------- /src/main/java/com/openapi/Basic/Return_Fields.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Basic; 2 | 3 | /** 4 | * Created by James on 2018/11/20. 5 | */ 6 | public enum Return_Fields { 7 | success, code, note,trackid,data,extent,size,from,total,format 8 | } 9 | -------------------------------------------------------------------------------- /src/main/resources/conf/args.properties: -------------------------------------------------------------------------------- 1 | ### environment 2 | mysql.driver=com.mysql.jdbc.Driver 3 | mysql.url=@mysql.url@ 4 | mysql.username=@mysql.username@ 5 | mysql.password=@mysql.password@ 6 | 7 | apikey = @apikey@ 8 | apiserver = @apiserver@ 9 | 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gptmgr 2 | chatgpt微信小程序后端 (前端代码:https://github.com/lolandkidtress/ai-code) 3 | 4 | demo请在微信小程序中搜索 AI懒人编程 5 | 6 | 基本功能: 7 | 调用openapi接口回答用户问题,可以限制用户每日次数限制,可以用邀请码进行推广 8 | 9 | 10 | 支持远程指导部署(有偿!有偿!有偿!) 11 | 12 | 咨询请扫码添加微信 13 | 14 | 15 | ![10501676901784_ pic](https://user-images.githubusercontent.com/3366494/220128638-32e03d47-3c18-465b-af87-a0455ac91228.jpg) 16 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/Basic/SystemConstant.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Basic; 2 | 3 | public class SystemConstant { 4 | 5 | 6 | public static final String accessToken = "at"; 7 | 8 | public static final String dot = "."; 9 | public static final String header_timestatmp = "t"; 10 | public static final String header_nonce = "n"; 11 | 12 | public static final String userid = "userid"; 13 | 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/Model/CodeUserQuota.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Model; 2 | 3 | import java.util.Date; 4 | import java.util.UUID; 5 | 6 | import lombok.Data; 7 | 8 | 9 | @Data 10 | public class CodeUserQuota { 11 | private String id = UUID.randomUUID().toString().replace("-",""); 12 | 13 | private Integer deleteflg = 0; 14 | 15 | private Date updatetime = new Date(); 16 | 17 | private String openid; 18 | 19 | private int cnt; 20 | 21 | private int maxcnt; 22 | 23 | 24 | } -------------------------------------------------------------------------------- /src/main/java/com/openapi/Dao/InviteCodeMapper.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Dao; 2 | 3 | import org.apache.ibatis.annotations.Param; 4 | 5 | import com.openapi.Model.InviteCode; 6 | 7 | 8 | public interface InviteCodeMapper { 9 | int count(@Param(value = "code") String code); 10 | 11 | int insert(InviteCode record); 12 | 13 | InviteCode getByCode(@Param(value = "code") String code, @Param(value = "consumeopenId") String consumeopenId); 14 | 15 | InviteCode selectById(@Param(value = "id") String id); 16 | 17 | 18 | } -------------------------------------------------------------------------------- /src/main/java/com/openapi/Model/ChatHist.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Model; 2 | 3 | import java.util.Date; 4 | import java.util.UUID; 5 | 6 | import lombok.Data; 7 | 8 | 9 | @Data 10 | public class ChatHist { 11 | private String id = UUID.randomUUID().toString().replace("-",""); 12 | 13 | private Integer deleteflg = 0; 14 | 15 | private Date createtime = new Date(); 16 | 17 | private Date updatetime = new Date(); 18 | 19 | private String question; 20 | 21 | private String openid; 22 | 23 | private String result; 24 | 25 | 26 | } -------------------------------------------------------------------------------- /src/main/java/com/openapi/Model/InviteCode.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Model; 2 | 3 | import java.util.Date; 4 | import java.util.UUID; 5 | 6 | import lombok.Data; 7 | 8 | 9 | @Data 10 | public class InviteCode { 11 | 12 | private String id = UUID.randomUUID().toString().replace("-",""); 13 | 14 | private Integer deleteflg = 0; 15 | 16 | private Date createtime = new Date(); 17 | 18 | private Date updatetime = new Date(); 19 | 20 | // code的主人 21 | private String produceopenid ; 22 | // 邀请的好友 23 | private String consumeopenid ; 24 | private String code; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/Dao/CodeUserQuotaMapper.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Dao; 2 | 3 | import java.util.Map; 4 | 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | import com.openapi.Model.CodeUserQuota; 8 | 9 | 10 | public interface CodeUserQuotaMapper { 11 | int count(Map param); 12 | 13 | int deleteByOpenId(@Param(value = "openid") String openid); 14 | 15 | int upsert(CodeUserQuota record); 16 | 17 | 18 | CodeUserQuota selectById(@Param(value = "id") String id); 19 | 20 | CodeUserQuota getCodeUserQuotaByOpenId(@Param(value = "openid") String openId); 21 | 22 | 23 | } -------------------------------------------------------------------------------- /src/main/java/com/openapi/Dao/CodeUserMapper.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Dao; 2 | 3 | import java.util.Map; 4 | 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | import com.openapi.Model.CodeUser; 8 | 9 | 10 | public interface CodeUserMapper { 11 | int count(Map param); 12 | 13 | int deleteByOpenId(@Param(value = "openid") String openid); 14 | 15 | int upsert(CodeUser record); 16 | 17 | CodeUser selectById(@Param(value = "id") String id); 18 | 19 | CodeUser getCodeUserByOpenId(@Param(value = "openid") String openId); 20 | 21 | CodeUser getCodeUserByInviteCode(@Param(value = "invitecode") String invitecode); 22 | 23 | 24 | } -------------------------------------------------------------------------------- /src/main/java/com/openapi/Model/CodeUser.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Model; 2 | 3 | import java.util.Date; 4 | import java.util.UUID; 5 | 6 | import lombok.Data; 7 | 8 | 9 | @Data 10 | public class CodeUser { 11 | private String id = UUID.randomUUID().toString().replace("-",""); 12 | 13 | private Integer deleteflg = 0; 14 | 15 | private Date createtime = new Date(); 16 | 17 | private Date updatetime = new Date(); 18 | 19 | private String username; 20 | 21 | private String openid; 22 | 23 | private String unionid; 24 | 25 | private String appid; 26 | 27 | private String apikey; 28 | 29 | // 邀请码 30 | private String invitecode; 31 | 32 | } -------------------------------------------------------------------------------- /src/main/java/com/openapi/App.java: -------------------------------------------------------------------------------- 1 | package com.openapi; 2 | 3 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | import org.springframework.boot.web.servlet.ServletComponentScan; 7 | import org.springframework.context.annotation.ComponentScan; 8 | 9 | 10 | @EnableAutoConfiguration 11 | @ComponentScan(basePackages = {"com.openapi.*"}) 12 | @ServletComponentScan({"com.openapi.*"}) 13 | @SpringBootApplication 14 | public class App { 15 | public static void main(String[] args) { 16 | 17 | System.setProperty("server.servlet.context-path", "/GPTMGR"); 18 | 19 | SpringApplicationBuilder builder = new SpringApplicationBuilder(App.class); 20 | 21 | builder.headless(false).run(args); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/Basic/BasicCode.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Basic; 2 | 3 | /** 4 | * Created by James on 16/5/23. 5 | */ 6 | public enum BasicCode { 7 | success(10200, "成功"), // 8 | 9 | data_not_found(10300, "无数据"), 10 | data_exist(10300, "数据已存在"), 11 | 12 | parameters_incorrect(10400, "参数格式不正确"), 13 | AUTH_FAIL(10401, "无权限访问"), 14 | 15 | error(10500,"失败"), 16 | code_invalid(10501,"验证码错误"), 17 | 18 | quota_over_limit(10600,"次数已用尽"); 19 | 20 | 21 | //20000 参数方法返回值错误 22 | 23 | 24 | 25 | public String note; 26 | public Integer code; 27 | 28 | private BasicCode(Integer code, String note) { 29 | this.note = note; 30 | this.code = code; 31 | } 32 | 33 | public Integer getCode(){ 34 | return this.code; 35 | } 36 | 37 | public String getNote(){ 38 | return this.note; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | logs 6 | 7 | mgr 8 | 9 | 10 | 11 | 12 | 13 | 15 | 16 | 19 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /src/main/resources/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /src/main/resources/db_init.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | // nohup java -jar /home/java/mgr/TCG.jar >> nohup.log 2>&1 & 4 | 5 | CREATE TABLE CodeUser 6 | ( id VARCHAR(32) NOT NULL PRIMARY KEY, 7 | deleteflg BIGINT(1) NOT NULL DEFAULT '0' , 8 | createtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , 9 | updatetime TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP , 10 | openid VARCHAR(32) , 11 | unionid VARCHAR(32), 12 | appid VARCHAR(32), 13 | apikey VARCHAR(32) 14 | ) ENGINE = InnoDB; 15 | 16 | alter table CodeUser add unique key pk_CodeUser (openid); 17 | 18 | CREATE TABLE CodeUserQuota 19 | ( id VARCHAR(32) NOT NULL PRIMARY KEY, 20 | deleteflg BIGINT(1) NOT NULL DEFAULT '0' , 21 | updatetime TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP , 22 | openid VARCHAR(32) , 23 | cnt int, 24 | maxcnt int 25 | ) ENGINE = InnoDB; 26 | alter table CodeUserQuota add unique key pk_CodeUserQuota (openid); 27 | 28 | 29 | alter table CodeUser add invitecode VARCHAR(32); 30 | 31 | CREATE TABLE InviteCode 32 | ( id VARCHAR(32) NOT NULL PRIMARY KEY, 33 | deleteflg BIGINT(1) NOT NULL DEFAULT '0' , 34 | createtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , 35 | updatetime TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP , 36 | code VARCHAR(32) , 37 | produceopenid VARCHAR(32), 38 | consumeopenid VARCHAR(32) 39 | ) ENGINE = InnoDB; 40 | alter table InviteCode add unique key pk_InviteCode (produceopenid,code,consumeopenid); 41 | 42 | 43 | CREATE TABLE ChatHist 44 | ( id VARCHAR(32) NOT NULL PRIMARY KEY, 45 | deleteflg BIGINT(1) NOT NULL DEFAULT '0' , 46 | createtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , 47 | updatetime TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP , 48 | openid VARCHAR(32) , 49 | question VARCHAR(32), 50 | result text 51 | ) ENGINE = InnoDB; -------------------------------------------------------------------------------- /src/main/java/com/openapi/tools/OkHttpClientUtil/SSLUtil.java: -------------------------------------------------------------------------------- 1 | package com.openapi.tools.OkHttpClientUtil; 2 | 3 | import java.security.SecureRandom; 4 | import java.security.cert.CertificateException; 5 | import java.security.cert.X509Certificate; 6 | 7 | import javax.net.ssl.HostnameVerifier; 8 | import javax.net.ssl.SSLContext; 9 | import javax.net.ssl.SSLSession; 10 | import javax.net.ssl.SSLSocketFactory; 11 | import javax.net.ssl.TrustManager; 12 | import javax.net.ssl.X509TrustManager; 13 | 14 | 15 | //https://www.jianshu.com/p/8a16ac7ee444 16 | public class SSLUtil { 17 | public static SSLSocketFactory createSSLSocketFactory() { 18 | SSLSocketFactory sSLSocketFactory = null; 19 | try { 20 | SSLContext sc = SSLContext.getInstance("TLS"); 21 | sc.init(null, new TrustManager[]{new TrustAllManager()}, new SecureRandom()); 22 | sSLSocketFactory = sc.getSocketFactory(); 23 | } catch (Exception ignored) { 24 | } 25 | return sSLSocketFactory; 26 | } 27 | 28 | public static class TrustAllManager implements X509TrustManager { 29 | @Override 30 | public void checkClientTrusted(X509Certificate[] chain, String authType) 31 | throws CertificateException { 32 | } 33 | @Override 34 | public void checkServerTrusted(X509Certificate[] chain, String authType) 35 | throws CertificateException { 36 | } 37 | 38 | @Override 39 | public X509Certificate[] getAcceptedIssuers() { 40 | return new X509Certificate[0]; 41 | } 42 | } 43 | 44 | public static class TrustAllHostnameVerifier implements HostnameVerifier { 45 | @Override 46 | public boolean verify(String hostname, SSLSession session) { 47 | return true; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/resources/mapping/ChatHistMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | id, deleteflg, createtime, updatetime,openid, question,result 17 | 18 | 19 | 20 | insert into ChatHist 21 | 22 | 23 | id, 24 | 25 | 26 | createtime, 27 | 28 | 29 | openid, 30 | 31 | 32 | question, 33 | 34 | 35 | result, 36 | 37 | 38 | 39 | 40 | #{id,jdbcType=VARCHAR}, 41 | 42 | 43 | #{createtime,jdbcType=TIMESTAMP}, 44 | 45 | 46 | #{openid,jdbcType=VARCHAR}, 47 | 48 | 49 | #{question,jdbcType=VARCHAR}, 50 | 51 | 52 | #{result,jdbcType=VARCHAR}, 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/tools/CommonUtils.java: -------------------------------------------------------------------------------- 1 | package com.openapi.tools; 2 | 3 | import java.nio.charset.Charset; 4 | import java.nio.charset.StandardCharsets; 5 | import java.security.MessageDigest; 6 | import java.security.NoSuchAlgorithmException; 7 | import java.time.ZoneId; 8 | 9 | 10 | public class CommonUtils { 11 | 12 | public final static ZoneId ZONDID = ZoneId.of( "GMT+08:00" ); 13 | public final static Charset CHARSET = StandardCharsets.UTF_8; 14 | public final static String SLASH = System.getProperty("file.separator"); 15 | public final static String UNDERLINE = "_"; 16 | public final static String HYPHEN = "-"; 17 | public final static String COLON = ":"; 18 | public final static String DEFAULTVERSION = "defaultVersion"; 19 | public final static String HTTP_PROTOCOL_PREFIX = "http://"; 20 | 21 | 22 | public static String byteArrayToHex(byte[] byteArray) { 23 | 24 | // 首先初始化一个字符数组,用来存放每个16进制字符 25 | char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' }; 26 | 27 | // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方)) 28 | char[] resultCharArray =new char[byteArray.length * 2]; 29 | 30 | // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去 31 | int index = 0; 32 | for (byte b : byteArray) { 33 | resultCharArray[index++] = hexDigits[b>>> 4 & 0xf]; 34 | resultCharArray[index++] = hexDigits[b& 0xf]; 35 | } 36 | // 字符数组组合成字符串返回 37 | return new String(resultCharArray); 38 | } 39 | 40 | public static String generalMD5(String input){ 41 | try { 42 | // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”) 43 | MessageDigest messageDigest = MessageDigest.getInstance("MD5"); 44 | 45 | // 输入的字符串转换成字节数组 46 | byte[] inputByteArray = input.getBytes(); 47 | 48 | // inputByteArray是输入字符串转换得到的字节数组 49 | messageDigest.update(inputByteArray); 50 | 51 | // 转换并返回结果,也是字节数组,包含16个元素 52 | byte[] resultByteArray = messageDigest.digest(); 53 | 54 | // 字符数组转换成字符串返回 55 | return byteArrayToHex(resultByteArray); 56 | } catch (NoSuchAlgorithmException e) { 57 | //异常就原样返回 58 | return input; 59 | } 60 | } 61 | 62 | //生成加盐的MD5 63 | public static String generalNonce(String s,String salt){ 64 | 65 | return CommonUtils.generalMD5(CommonUtils.generalMD5(s.concat(salt))); 66 | } 67 | 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/resources/mapping/InviteCodeMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | id, deleteflg, createtime, updatetime, code, produceopenid,consumeopenid 16 | 17 | 24 | 33 | 34 | 41 | 42 | 43 | 44 | insert into InviteCode 45 | 46 | 47 | id, 48 | 49 | 50 | createtime, 51 | 52 | 53 | code, 54 | 55 | 56 | produceopenid, 57 | 58 | 59 | consumeopenid, 60 | 61 | 62 | 63 | 64 | #{id,jdbcType=VARCHAR}, 65 | 66 | 67 | #{createtime,jdbcType=TIMESTAMP}, 68 | 69 | 70 | #{code,jdbcType=VARCHAR}, 71 | 72 | 73 | #{produceopenid,jdbcType=VARCHAR}, 74 | 75 | 76 | #{consumeopenid,jdbcType=VARCHAR}, 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/main/resources/mapping/CodeUserQuotaMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | id, deleteflg, updatetime, cnt,openid,maxcnt 16 | 17 | 24 | 32 | 33 | 38 | 39 | update CodeUserQuota set deleteflg = 1,updatetime = CURRENT_TIMESTAMP 40 | where openid = #{openid,jdbcType=VARCHAR} 41 | 42 | 43 | insert into CodeUserQuota 44 | 45 | 46 | id, 47 | 48 | 49 | updatetime, 50 | 51 | 52 | openid, 53 | 54 | 55 | cnt, 56 | 57 | 58 | maxcnt, 59 | 60 | 61 | 62 | 63 | #{id,jdbcType=VARCHAR}, 64 | 65 | 66 | #{updatetime,jdbcType=TIMESTAMP}, 67 | 68 | 69 | #{openid,jdbcType=VARCHAR}, 70 | 71 | 72 | #{cnt,jdbcType=BIGINT}, 73 | 74 | 75 | #{maxcnt,jdbcType=BIGINT}, 76 | 77 | 78 | ON DUPLICATE KEY UPDATE 79 | 80 | 81 | updatetime = #{updatetime,jdbcType=TIMESTAMP}, 82 | 83 | 84 | cnt = #{cnt,jdbcType=BIGINT}, 85 | 86 | 87 | maxcnt = #{maxcnt,jdbcType=BIGINT}, 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/Basic/JsonConvert.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Basic; 2 | 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import org.apache.logging.log4j.LogManager; 10 | import org.apache.logging.log4j.Logger; 11 | 12 | import com.fasterxml.jackson.core.JsonParseException; 13 | import com.fasterxml.jackson.core.JsonParser; 14 | import com.fasterxml.jackson.core.JsonProcessingException; 15 | import com.fasterxml.jackson.core.type.TypeReference; 16 | import com.fasterxml.jackson.databind.DeserializationFeature; 17 | import com.fasterxml.jackson.databind.JsonMappingException; 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import com.fasterxml.jackson.databind.SerializationFeature; 20 | 21 | 22 | /** 23 | * Created by James on 16/5/23. 24 | */ 25 | public class JsonConvert { 26 | private static final Logger LOGGER = LogManager.getLogger(JsonConvert.class.getName()); 27 | private final static ObjectMapper objectMapper = new ObjectMapper(); 28 | 29 | static { 30 | // TODO 是否需要时间转换 默认时间戳 31 | objectMapper.setDateFormat(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); 32 | // 允许单引号 33 | objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); 34 | // 允许反斜杆等字符 35 | objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); 36 | //允许数组 37 | objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,true); 38 | // 允许出现对象中没有的字段 39 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 40 | // No serializer found for class XXXX and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) 41 | objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); 42 | //pretty-printing 43 | objectMapper.enable(SerializationFeature.INDENT_OUTPUT); 44 | } 45 | 46 | private JsonConvert() { 47 | } 48 | 49 | public static String toJson(Object object) { 50 | try { 51 | //return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object); 52 | return objectMapper.writeValueAsString(object); 53 | } catch (JsonProcessingException e) { 54 | LOGGER.error("对象转json失败", e); 55 | } 56 | return ""; 57 | } 58 | 59 | public static T toObject(String json, Class valueType) throws JsonParseException, JsonMappingException, IOException { 60 | return objectMapper.readValue(json, valueType); 61 | } 62 | 63 | @SuppressWarnings("unchecked") 64 | public static T toObject(String json, TypeReference typeReference) throws JsonParseException, 65 | JsonMappingException, IOException { 66 | return (T) objectMapper.readValue(json, typeReference); 67 | } 68 | 69 | public static void main(String[] args) throws Exception{ 70 | Map map = new HashMap(); 71 | map.put("内容","回车测试\\n车1"); 72 | List list= new ArrayList<>(); 73 | list.add(map); 74 | 75 | String a = JsonConvert.toJson(list); 76 | System.out.println(a); 77 | 78 | List b = JsonConvert.toObject(a,List.class); 79 | b.get(0); 80 | 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/Database/TgDataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Database; 2 | 3 | import org.apache.ibatis.session.SqlSessionFactory; 4 | import org.apache.logging.log4j.LogManager; 5 | import org.apache.logging.log4j.Logger; 6 | import org.mybatis.spring.SqlSessionFactoryBean; 7 | import org.mybatis.spring.annotation.MapperScan; 8 | import org.springframework.beans.factory.annotation.Qualifier; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.context.annotation.Primary; 13 | import org.springframework.context.annotation.PropertySource; 14 | import org.springframework.core.io.ClassPathResource; 15 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 16 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 17 | 18 | import com.alibaba.druid.pool.DruidDataSource; 19 | 20 | import javax.sql.DataSource; 21 | 22 | 23 | @Configuration 24 | @PropertySource("classpath:conf/args.properties") 25 | @MapperScan(basePackages = "com.openapi.Dao", sqlSessionFactoryRef = "huarongdaoSqlSessionFactory") 26 | public class TgDataSourceConfig { 27 | private final static Logger log = LogManager.getLogger(TgDataSourceConfig.class.getName()); 28 | private String resource = "mybatis-config.xml"; 29 | private String mapper = "classpath:mapping/*.xml"; 30 | 31 | @Value("${mysql.driver}") 32 | private String driverClass; 33 | 34 | @Value("${mysql.url}") 35 | private String url; 36 | 37 | @Value("${mysql.username}") 38 | private String user; 39 | 40 | @Value("${mysql.password}") 41 | private String password; 42 | 43 | @Value("${apikey}") 44 | private String apikey; 45 | 46 | 47 | @Value("${apiserver}") 48 | private String apiserver; 49 | 50 | @Primary 51 | @Bean(name = "huarongdaoDataSource") 52 | public DataSource clusterDataSource() { 53 | DruidDataSource dataSource = new DruidDataSource(); 54 | dataSource.setDriverClassName(driverClass); 55 | dataSource.setUrl(url); 56 | dataSource.setUsername(user); 57 | dataSource.setPassword(password); 58 | dataSource.setMinIdle(5); 59 | dataSource.setInitialSize(5); 60 | return dataSource; 61 | } 62 | 63 | @Primary 64 | @Bean(name = "huarongdaoTransactionManager") 65 | public DataSourceTransactionManager clusterTransactionManager() { 66 | return new DataSourceTransactionManager(clusterDataSource()); 67 | } 68 | 69 | @Primary 70 | @Bean(name = "huarongdaoSqlSessionFactory") 71 | public SqlSessionFactory readDataSource(@Qualifier("huarongdaoDataSource") DataSource secondDataSource) { 72 | try { 73 | SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 74 | sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(resource)); 75 | sqlSessionFactoryBean.setDataSource(secondDataSource); 76 | sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver() 77 | .getResources(mapper)); 78 | return sqlSessionFactoryBean.getObject(); 79 | } catch (Exception e) { 80 | log.error("注解mybatis读取数据异常", e); 81 | return null; 82 | } 83 | } 84 | 85 | public String getApikey() { 86 | return apikey; 87 | } 88 | 89 | public String getApiserver() { 90 | return apiserver; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/tools/ThreadLocalUtil.java: -------------------------------------------------------------------------------- 1 | package com.openapi.tools; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.Set; 8 | 9 | 10 | /** 11 | * @author wendong 12 | * @email wendong@juxinli.com 13 | * @date 2017/5/23. 14 | */ 15 | public final class ThreadLocalUtil { 16 | private static final ThreadLocal threadLocal = new ThreadLocal() { 17 | @Override 18 | protected HashMap initialValue() { 19 | return new HashMap(4); 20 | } 21 | }; 22 | 23 | public static Object getThreadLocal() { 24 | return threadLocal.get(); 25 | } 26 | 27 | public static void setThreadLocal(Object local) { 28 | threadLocal.set(local); 29 | } 30 | 31 | public static T get(String key) { 32 | Map map = (Map) threadLocal.get(); 33 | return (T) map.get(key); 34 | } 35 | 36 | public static T getIfAbsent(String key) { 37 | Map map = (Map) threadLocal.get(); 38 | if(map!=null){ 39 | return (T) map.getOrDefault(key,""); 40 | }else { 41 | return (T) ""; 42 | } 43 | } 44 | 45 | public static T getOrDefault(String key,String defaluValue) { 46 | Map map = (Map) threadLocal.get(); 47 | if(map!=null){ 48 | return (T) map.getOrDefault(key,defaluValue); 49 | }else { 50 | return (T) ""; 51 | } 52 | } 53 | 54 | public static boolean isExist(String key) { 55 | Map map = (Map) threadLocal.get(); 56 | if(map!=null){ 57 | return map.containsKey(key); 58 | }else { 59 | return false; 60 | } 61 | } 62 | 63 | public static void set(String key, Object value) { 64 | Map map = (Map) threadLocal.get(); 65 | map.put(key, value); 66 | } 67 | 68 | public static void set(Map keyValueMap) { 69 | Map map = (Map) threadLocal.get(); 70 | map.putAll(keyValueMap); 71 | } 72 | 73 | public static void remove() { 74 | threadLocal.remove(); 75 | } 76 | 77 | public static Map fetchVarsByPrefix(String prefix) { 78 | Map vars = new HashMap<>(); 79 | if (prefix == null) { 80 | return vars; 81 | } 82 | Map map = (Map) threadLocal.get(); 83 | Set set = map.entrySet(); 84 | 85 | for (Map.Entry entry : set) { 86 | Object key = entry.getKey(); 87 | if (key instanceof String) { 88 | if (((String) key).startsWith(prefix)) { 89 | vars.put((String) key, (T) entry.getValue()); 90 | } 91 | } 92 | } 93 | return vars; 94 | } 95 | 96 | public static T remove(String key) { 97 | Map map = (Map) threadLocal.get(); 98 | return (T) map.remove(key); 99 | } 100 | 101 | public static void clear(String prefix) { 102 | if (prefix == null) { 103 | return; 104 | } 105 | Map map = (Map) threadLocal.get(); 106 | Set set = map.entrySet(); 107 | List removeKeys = new ArrayList<>(); 108 | 109 | for (Map.Entry entry : set) { 110 | Object key = entry.getKey(); 111 | if (key instanceof String) { 112 | if (((String) key).startsWith(prefix)) { 113 | removeKeys.add((String) key); 114 | } 115 | } 116 | } 117 | for (String key : removeKeys) { 118 | map.remove(key); 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.openai 8 | gptmgr 9 | 1.0-SNAPSHOT 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 2.7.6 15 | 16 | 17 | 18 | 19 | org.apache.logging.log4j 20 | log4j-core 21 | 2.17.2 22 | 23 | 24 | org.apache.logging.log4j 25 | log4j-core 26 | 2.17.2 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-logging 36 | 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-thymeleaf 42 | 43 | 44 | org.mybatis.spring.boot 45 | mybatis-spring-boot-starter 46 | 1.1.1 47 | 48 | 49 | org.projectlombok 50 | lombok 51 | 1.18.0 52 | 53 | 54 | com.google.guava 55 | guava 56 | 27.1-jre 57 | 58 | 59 | com.alibaba 60 | druid 61 | 1.1.8 62 | 63 | 64 | mysql 65 | mysql-connector-java 66 | 5.1.49 67 | 68 | 69 | commons-codec 70 | commons-codec 71 | 1.10 72 | 73 | 74 | dom4j 75 | dom4j 76 | 1.6.1 77 | 78 | 79 | 80 | com.squareup.okhttp3 81 | okhttp 82 | 4.9.3 83 | 84 | 85 | 86 | com.squareup.okhttp3 87 | okhttp-tls 88 | 4.9.3 89 | 90 | 91 | 92 | 93 | MGR 94 | compile 95 | src/main/java 96 | 97 | 98 | org.springframework.boot 99 | spring-boot-maven-plugin 100 | 101 | 102 | 103 | 104 | 105 | 106 | src/main/resources 107 | true 108 | 109 | 110 | src/main/resources 111 | ${project.build.directory} 112 | true 113 | 114 | 115 | src/main/webapp 116 | ${project.build.directory}/src/main/webapp 117 | true 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/tools/XmlToJson.java: -------------------------------------------------------------------------------- 1 | package com.openapi.tools; 2 | 3 | import java.util.HashMap; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import org.dom4j.Document; 9 | import org.dom4j.DocumentHelper; 10 | import org.dom4j.Element; 11 | 12 | import com.openapi.Basic.JsonConvert; 13 | 14 | 15 | public class XmlToJson { 16 | 17 | 18 | /** 19 | * 转换一个xml格式的字符串到json格式 20 | * 21 | * @param xml xml格式的字符串 22 | * @return 成功返回json 格式的字符串;失败反回null 23 | */ 24 | public static Map xml2Json(String xml) { 25 | try { 26 | Document doc = DocumentHelper.parseText(xml); 27 | Element root = doc.getRootElement(); 28 | return iterateElement(root); 29 | } catch (Exception e) { 30 | e.printStackTrace(); 31 | return null; 32 | } 33 | } 34 | 35 | public static String xml2JsonStr(String xml) { 36 | try { 37 | Document doc = DocumentHelper.parseText(xml); 38 | Element root = doc.getRootElement(); 39 | return JsonConvert.toJson(iterateElement(root)); 40 | } catch (Exception e) { 41 | e.printStackTrace(); 42 | return null; 43 | } 44 | } 45 | 46 | /** 47 | * 一个迭代方法 48 | */ 49 | private static Map iterateElement(Element element) { 50 | List jiedian = element.elements(); 51 | Element et; 52 | Map obj = new HashMap(); 53 | Object temp; 54 | List list; 55 | for (Object o : jiedian) { 56 | list = new LinkedList(); 57 | et = (Element) o; 58 | if ("".equals(et.getTextTrim())) { 59 | if (et.elements().size() == 0) { 60 | continue; 61 | } 62 | if (obj.containsKey(et.getName())) { 63 | temp = obj.get(et.getName()); 64 | if (temp instanceof List) { 65 | list = (List) temp; 66 | list.add(iterateElement(et)); 67 | } else if (temp instanceof Map) { 68 | list.add((HashMap) temp); 69 | list.add(iterateElement(et)); 70 | } else { 71 | list.add((String) temp); 72 | list.add(iterateElement(et)); 73 | } 74 | obj.put(et.getName(), list); 75 | } else { 76 | obj.put(et.getName(), iterateElement(et)); 77 | } 78 | } else { 79 | if (obj.containsKey(et.getName())) { 80 | temp = obj.get(et.getName()); 81 | if (temp instanceof List) { 82 | list = (List) temp; 83 | list.add(et.getTextTrim()); 84 | } else if (temp instanceof Map) { 85 | list.add((HashMap) temp); 86 | list.add(iterateElement(et)); 87 | } else { 88 | list.add((String) temp); 89 | list.add(et.getTextTrim()); 90 | } 91 | obj.put(et.getName(), list); 92 | } else { 93 | obj.put(et.getName(), et.getTextTrim()); 94 | } 95 | 96 | } 97 | 98 | } 99 | return obj; 100 | } 101 | 102 | // 测试 103 | public static void main(String[] args) { 104 | String xmlStr = "" + 105 | "
" + 106 | "MDM" + 107 | "MDM" + 108 | "" + 109 | "DAXT" + 110 | "1" + 111 | "ADD" + 112 | "ORG" + 113 | "" + 114 | "checkCode" 115 | + "" + 116 | "
" + 117 | "" + 118 | "" + 119 | "460c5239-13f662e8f67-2f1936027f000a1d675dd1399911234" + 120 | "" + 121 | "" + 122 | "460c5239-13f662e8f67-2f1936027f000a1d675dd139991369c4" + 123 | "" + 124 | "" + 125 | "
"; 126 | 127 | System.out.println(XmlToJson.xml2JsonStr(xmlStr)); 128 | } 129 | } -------------------------------------------------------------------------------- /src/main/resources/mapping/CodeUserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | id, deleteflg, createtime, updatetime, appid,openid, unionid,apikey,invitecode 18 | 19 | 26 | 34 | 35 | 43 | 44 | 49 | 50 | update CodeUser set deleteflg = 1,updatetime = CURRENT_TIMESTAMP 51 | where openid = #{openid,jdbcType=VARCHAR} 52 | 53 | 54 | insert into CodeUser 55 | 56 | 57 | id, 58 | 59 | 60 | createtime, 61 | 62 | 63 | appid, 64 | 65 | 66 | openid, 67 | 68 | 69 | unionid, 70 | 71 | 72 | apikey, 73 | 74 | 75 | invitecode, 76 | 77 | 78 | 79 | 80 | #{id,jdbcType=VARCHAR}, 81 | 82 | 83 | #{createtime,jdbcType=TIMESTAMP}, 84 | 85 | 86 | #{appid,jdbcType=VARCHAR}, 87 | 88 | 89 | #{openid,jdbcType=VARCHAR}, 90 | 91 | 92 | #{unionid,jdbcType=VARCHAR}, 93 | 94 | 95 | #{apikey,jdbcType=VARCHAR}, 96 | 97 | 98 | #{invitecode,jdbcType=VARCHAR}, 99 | 100 | 101 | ON DUPLICATE KEY UPDATE 102 | 103 | 104 | updatetime = #{updatetime,jdbcType=TIMESTAMP}, 105 | 106 | 107 | appid = #{appid,jdbcType=VARCHAR}, 108 | 109 | 110 | openid = #{openid,jdbcType=VARCHAR}, 111 | 112 | 113 | unionid = #{unionid,jdbcType=VARCHAR}, 114 | 115 | 116 | apikey = #{apikey,jdbcType=VARCHAR}, 117 | 118 | 119 | invitecode = #{invitecode,jdbcType=VARCHAR}, 120 | 121 | 122 | deleteflg = #{deleteflg,jdbcType=BIGINT}, 123 | 124 | 125 | 126 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/tools/OkHttpClientUtil/SSLSocketClient.java: -------------------------------------------------------------------------------- 1 | package com.openapi.tools.OkHttpClientUtil; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.security.GeneralSecurityException; 6 | import java.security.KeyStore; 7 | import java.security.cert.Certificate; 8 | import java.security.cert.CertificateFactory; 9 | import java.util.Arrays; 10 | import java.util.Collection; 11 | 12 | import javax.net.ssl.HostnameVerifier; 13 | import javax.net.ssl.KeyManagerFactory; 14 | import javax.net.ssl.SSLSession; 15 | import javax.net.ssl.SSLSocketFactory; 16 | import javax.net.ssl.TrustManager; 17 | import javax.net.ssl.TrustManagerFactory; 18 | import javax.net.ssl.X509TrustManager; 19 | import okhttp3.tls.HandshakeCertificates; 20 | import okio.Buffer; 21 | 22 | 23 | public class SSLSocketClient { 24 | 25 | private static HandshakeCertificates clientCertificates; 26 | 27 | static{ 28 | clientCertificates = new HandshakeCertificates.Builder() 29 | .addPlatformTrustedCertificates() 30 | .build(); 31 | } 32 | //获取这个SSLSocketFactory 33 | public static SSLSocketFactory getSSLSocketFactory() { 34 | try { 35 | 36 | return clientCertificates.sslSocketFactory(); 37 | 38 | // SSLContext sslContext = SSLContext.getInstance("SSL"); 39 | // sslContext.init(null, getTrustManager(), new SecureRandom()); 40 | // return sslContext.getSocketFactory(); 41 | } catch (Exception e) { 42 | throw new RuntimeException(e); 43 | } 44 | } 45 | 46 | //获取这个SSLSocketFactory 47 | public static X509TrustManager getTrustManager() { 48 | try { 49 | 50 | return clientCertificates.trustManager(); 51 | 52 | // SSLContext sslContext = SSLContext.getInstance("SSL"); 53 | // sslContext.init(null, getTrustManager(), new SecureRandom()); 54 | // return sslContext.getSocketFactory(); 55 | } catch (Exception e) { 56 | throw new RuntimeException(e); 57 | } 58 | } 59 | 60 | public static HostnameVerifier getHostnameVerifier() { 61 | HostnameVerifier hostnameVerifier = new HostnameVerifier() { 62 | @Override 63 | public boolean verify(String s, SSLSession sslSession) { 64 | return true; 65 | } 66 | }; 67 | return hostnameVerifier; 68 | } 69 | 70 | 71 | public static X509TrustManager trustManagerForCertificates(String str_cert) 72 | throws GeneralSecurityException { 73 | 74 | InputStream in = new Buffer() 75 | .writeUtf8(str_cert) 76 | .inputStream(); 77 | 78 | CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); 79 | Collection certificates = certificateFactory.generateCertificates(in); 80 | if (certificates.isEmpty()) { 81 | throw new IllegalArgumentException("expected non-empty set of trusted certificates"); 82 | } 83 | 84 | // Put the certificates a key store. 85 | char[] password = "password".toCharArray(); // Any password will work. 86 | KeyStore keyStore = newEmptyKeyStore(password); 87 | int index = 0; 88 | for (Certificate certificate : certificates) { 89 | String certificateAlias = Integer.toString(index++); 90 | keyStore.setCertificateEntry(certificateAlias, certificate); 91 | } 92 | 93 | // Use it to build an X509 trust manager. 94 | KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( 95 | KeyManagerFactory.getDefaultAlgorithm()); 96 | keyManagerFactory.init(keyStore, password); 97 | TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( 98 | TrustManagerFactory.getDefaultAlgorithm()); 99 | trustManagerFactory.init(keyStore); 100 | TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); 101 | if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { 102 | throw new IllegalStateException("Unexpected default trust managers:" 103 | + Arrays.toString(trustManagers)); 104 | } 105 | return (X509TrustManager) trustManagers[0]; 106 | } 107 | 108 | private static KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { 109 | try { 110 | KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 111 | InputStream in = null; // By convention, 'null' creates an empty key store. 112 | keyStore.load(in, password); 113 | return keyStore; 114 | } catch (IOException e) { 115 | throw new AssertionError(e); 116 | } 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/tools/NativePath.java: -------------------------------------------------------------------------------- 1 | package com.openapi.tools; 2 | 3 | import java.nio.file.Path; 4 | import java.nio.file.Paths; 5 | 6 | import org.apache.logging.log4j.LogManager; 7 | import org.apache.logging.log4j.Logger; 8 | 9 | 10 | public class NativePath { 11 | 12 | private static final Logger LOGGER = LogManager.getLogger(NativePath.class.getName()); 13 | 14 | /** 15 | * 获取配置文件路径 16 | * 17 | * class path为jar包的情况下,路径指向与jar包同级目录 jetty jar包独立部署方式,需要在maven中添加resources配置targetPath {project.build.directory} tomcat发布,需要将配置文件放在/WEB-INF下面 18 | * 19 | * @param path 20 | * 相对路径 21 | * @return 绝对路径 22 | */ 23 | public static Path get(String path) { 24 | if (path.startsWith("/")) { 25 | path = path.substring(1); 26 | } 27 | 28 | String java_class_path = get_class_path(); 29 | if (java_class_path.endsWith(".jar")) { 30 | int lastIndexOf = java_class_path.lastIndexOf("/"); 31 | if (lastIndexOf == -1) { 32 | java_class_path = ""; 33 | } else { 34 | java_class_path = java_class_path.substring(0, lastIndexOf); 35 | } 36 | } 37 | if (!java_class_path.isEmpty() && !java_class_path.endsWith("/")) { 38 | java_class_path = java_class_path.concat("/"); 39 | } 40 | java_class_path = java_class_path.concat(path); 41 | LOGGER.info("final path ---> :".concat(java_class_path)); 42 | return Paths.get(java_class_path); 43 | } 44 | 45 | public static String get_class_path(Class clazz) { 46 | String location = clazz.getProtectionDomain().getCodeSource().getLocation().getFile(); 47 | location = location.replace("file:", ""); 48 | if (System.getProperty("os.name").indexOf("Windows") != -1) { 49 | location = location.substring(1); 50 | } 51 | if (location.contains(".jar!")) { 52 | location = location.substring(0, location.indexOf(".jar!")).concat(".jar"); 53 | } 54 | if (location.endsWith("/")) { 55 | location = location.substring(0, location.length() - 1); 56 | } 57 | return location; 58 | } 59 | 60 | /** 61 | * 当前启动项目的class path (jar包地址或末尾不包含/的class文件夹地址) 62 | * 63 | * @return classpath 64 | */ 65 | public static String get_class_path() { 66 | String java_class_path = System.getProperty("java.class.path"); 67 | LOGGER.debug("java_class_path -> :".concat(java_class_path)); 68 | LOGGER.debug(System.getProperty("os.name")); 69 | if (System.getProperty("os.name").indexOf("Windows") != -1) { 70 | int indexof_classes = java_class_path.indexOf("\\classes"); 71 | if (indexof_classes != -1) { 72 | // 直接代码启动 73 | java_class_path = java_class_path.substring(0, indexof_classes).concat("\\classes"); 74 | int indexof_separator = java_class_path.lastIndexOf(";"); 75 | if (indexof_separator != -1) { 76 | java_class_path = java_class_path.substring(indexof_separator + 1); 77 | } 78 | LOGGER.debug("windows code start --> :".concat(java_class_path)); 79 | } else { 80 | String webroot = NativePath.class.getResource("").getFile(); 81 | webroot = webroot.replace("file:/", ""); 82 | int indexof_web_inf = webroot.indexOf("/WEB-INF/"); 83 | if (indexof_web_inf != -1) { 84 | // WEB容器启动 85 | java_class_path = webroot.substring(0, indexof_web_inf).concat("/WEB-INF/classes"); 86 | LOGGER.debug("windows server start --> :".concat(java_class_path)); 87 | } else { 88 | int comma = java_class_path.indexOf(";"); 89 | if (comma > 0) { 90 | java_class_path = java_class_path.substring(0, comma); 91 | } 92 | // JAR包启动 93 | LOGGER.debug("windows jar start --> :".concat(java_class_path)); 94 | } 95 | } 96 | } else {// LINUX 97 | int indexof_classes = java_class_path.indexOf("/classes"); 98 | if (indexof_classes != -1) { 99 | // 直接代码启动 100 | java_class_path = java_class_path.substring(0, indexof_classes).concat("/classes"); 101 | int indexof_separator = java_class_path.lastIndexOf(":"); 102 | if (indexof_separator != -1) { 103 | java_class_path = java_class_path.substring(indexof_separator + 1); 104 | } 105 | LOGGER.debug("linux code start --> :".concat(java_class_path)); 106 | } else { 107 | String webroot = NativePath.class.getResource("").getFile(); 108 | webroot = webroot.replace("file:", ""); 109 | int indexof_web_inf = webroot.indexOf("/WEB-INF/"); 110 | if (indexof_web_inf != -1) { 111 | // WEB容器启动 112 | java_class_path = webroot.substring(0, indexof_web_inf).concat("/WEB-INF/classes"); 113 | LOGGER.debug("linux server start --> :".concat(java_class_path)); 114 | } else { 115 | int comma = java_class_path.indexOf(":"); 116 | if (comma > 0) { 117 | java_class_path = java_class_path.substring(0, comma); 118 | } 119 | // JAR包启动 120 | LOGGER.debug("linux jar start --> :".concat(java_class_path)); 121 | } 122 | } 123 | } 124 | return java_class_path; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/Basic/Return.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Basic; 2 | 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import org.apache.logging.log4j.LogManager; 8 | import org.apache.logging.log4j.Logger; 9 | 10 | import com.fasterxml.jackson.core.type.TypeReference; 11 | 12 | 13 | /** 14 | * Created by James on 16/5/23. 15 | */ 16 | public class Return extends HashMap { 17 | private static final long serialVersionUID = 1L; 18 | private static final Logger LOGGER = LogManager.getLogger(Return.class.getName()); 19 | 20 | 21 | 22 | //////////////////////////////// create////////////////////////////////// 23 | public static Return create() { 24 | return new Return(); 25 | } 26 | 27 | public static Return create(String key, Object value) { 28 | return new Return().add(key, value); 29 | } 30 | 31 | public static Return create(String json) { 32 | Return jo = new Return(); 33 | try { 34 | Map fromJson = JsonConvert.toObject(json, new TypeReference>() { 35 | }); 36 | for (Entry entry : fromJson.entrySet()) { 37 | jo.put(entry.getKey(), entry.getValue()); 38 | } 39 | } catch (IOException e) { 40 | LOGGER.error("TReturn.create 解析 JSON 失败", e); 41 | return Return.FAIL(BasicCode.error); 42 | } 43 | return jo; 44 | } 45 | 46 | public static Return copy(Return ret){ 47 | return Return.create(ret.toJson()); 48 | } 49 | 50 | 51 | 52 | /////////////////////////////////////////// SUCCESS///////////////////////// 53 | 54 | public static Return SUCCESS(Integer code, String note) { 55 | Return jo = new Return(); 56 | jo.put(Return_Fields.success.name(), true); 57 | jo.put(Return_Fields.code.name(), code); 58 | jo.put(Return_Fields.note.name(), note); 59 | 60 | return jo; 61 | } 62 | 63 | public static Return SUCCESS(String json) { 64 | Return jo = create(json); 65 | jo.put(Return_Fields.success.name(), true); 66 | return jo; 67 | } 68 | //public boolean register(T node){ 69 | public static Return SUCCESS(T basicCode) { 70 | return SUCCESS(basicCode.code, basicCode.note); 71 | } 72 | 73 | ///////////////////////////////////////////////// FAIL//////////////////////////// 74 | public static Return FAIL(Integer code, String note) { 75 | Return jo = new Return(); 76 | jo.put(Return_Fields.success.name(), false); 77 | jo.put(Return_Fields.code.name(), code); 78 | jo.put(Return_Fields.note.name(), note); 79 | return jo; 80 | } 81 | 82 | public static Return FAIL(T basicCode) { 83 | return FAIL(basicCode.code, basicCode.note); 84 | } 85 | 86 | //////////////////////////////////// GETTER SETTER/////////////////////////// 87 | public Boolean is_success() { 88 | return (Boolean) this.getOrDefault(Return_Fields.success.name(), false); 89 | } 90 | 91 | public Integer get_code() { 92 | return (Integer) this.getOrDefault(Return_Fields.code.name(), BasicCode.error.code); 93 | } 94 | 95 | public String get_note() { 96 | return (String) this.getOrDefault(Return_Fields.note.name(), ""); 97 | } 98 | 99 | public Object get_data() { 100 | return this.getOrDefault(Return_Fields.data.name(), ""); 101 | } 102 | 103 | public String get_format() { 104 | return (String) this.getOrDefault(Return_Fields.format.name(), ""); 105 | } 106 | 107 | public Object get_extent() { 108 | return this.getOrDefault(Return_Fields.extent.name(), ""); 109 | } 110 | 111 | public int get_from() { 112 | return (Integer) this.getOrDefault(Return_Fields.from.name(), 0); 113 | } 114 | 115 | public int get_size() { 116 | return (Integer) this.getOrDefault(Return_Fields.size.name(), 0); 117 | } 118 | 119 | public int get_total() { 120 | return (Integer) this.getOrDefault(Return_Fields.total.name(), 0); 121 | } 122 | 123 | //////////////////////// @Override///////////////////////////////////// 124 | @Override 125 | public Return put(String key, Object value) { 126 | super.put(key, value); 127 | return this; 128 | } 129 | 130 | public Return add(String key, Object value) { 131 | super.put(key, value); 132 | return this; 133 | } 134 | 135 | public String toJson() { 136 | try { 137 | return JsonConvert.toJson(this); 138 | } catch (Exception e) { 139 | LOGGER.error("json 解析失败:", e); 140 | return JsonConvert.toJson(Return.FAIL(BasicCode.error)); 141 | } 142 | } 143 | 144 | public Return note(String note) { 145 | super.put(Return_Fields.note.name(), note); 146 | return this; 147 | } 148 | public Return data(Object data) { 149 | super.put(Return_Fields.data.name(), data); 150 | return this; 151 | } 152 | public Return from(int from) { 153 | super.put(Return_Fields.from.name(), from); 154 | return this; 155 | } 156 | public Return size(int size) { 157 | super.put(Return_Fields.size.name(), size); 158 | return this; 159 | } 160 | public Return total(int total) { 161 | super.put(Return_Fields.total.name(), total); 162 | return this; 163 | } 164 | public Return extent(String extent) { 165 | super.put(Return_Fields.extent.name(), extent); 166 | return this; 167 | } 168 | public Return format(String format) { 169 | super.put(Return_Fields.format.name(), format); 170 | return this; 171 | } 172 | public Return trackid(String trackid) { 173 | super.put(Return_Fields.trackid.name(), trackid); 174 | return this; 175 | } 176 | 177 | 178 | 179 | } 180 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/Controller/AICodeController.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Controller; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | import java.util.Random; 6 | 7 | import org.apache.logging.log4j.LogManager; 8 | import org.apache.logging.log4j.Logger; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.PostMapping; 12 | import org.springframework.web.bind.annotation.RequestBody; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | import com.google.common.base.Strings; 17 | import com.openapi.Basic.BasicCode; 18 | import com.openapi.Basic.JsonConvert; 19 | import com.openapi.Basic.Return; 20 | import com.openapi.Model.CodeUser; 21 | import com.openapi.Model.CodeUserQuota; 22 | import com.openapi.Service.CodeUserService; 23 | 24 | 25 | @RestController 26 | @RequestMapping("/aicode") 27 | public class AICodeController { 28 | 29 | private static Logger logger = LogManager.getLogger(AICodeController.class); 30 | 31 | @Autowired 32 | CodeUserService _codeUserService; 33 | 34 | @GetMapping("/getUser") 35 | public Return getUser(String openId) throws Exception { 36 | 37 | if(Strings.isNullOrEmpty(openId)){ 38 | return Return.FAIL(BasicCode.parameters_incorrect); 39 | } 40 | CodeUser user = _codeUserService.getCodeUserByOpenId(openId); 41 | if (user == null) { 42 | return Return.FAIL(BasicCode.data_not_found); 43 | } else { 44 | return Return.SUCCESS(BasicCode.success).data(user); 45 | } 46 | } 47 | 48 | @PostMapping("/register") 49 | public Return register(@RequestBody CodeUser user) throws Exception { 50 | 51 | if(Strings.isNullOrEmpty(user.getOpenid())){ 52 | return Return.FAIL(BasicCode.parameters_incorrect); 53 | } 54 | 55 | // 8位随机字符串 56 | int length = 8; 57 | String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 58 | Random random = new Random(); 59 | StringBuffer sb = new StringBuffer(); 60 | for (int i = 0; i < length; i++) { 61 | int number = random.nextInt(62); 62 | sb.append(str.charAt(number)); 63 | } 64 | String code = sb.toString(); 65 | 66 | user.setInvitecode(code); 67 | 68 | int cnt = _codeUserService.save(user); 69 | if (cnt <= 0) { 70 | return Return.FAIL(BasicCode.error); 71 | } else { 72 | return Return.SUCCESS(BasicCode.success).data(user); 73 | } 74 | } 75 | 76 | @GetMapping("/getQuota") 77 | public Return getQuota(String openId) { 78 | 79 | if(Strings.isNullOrEmpty(openId)){ 80 | return Return.FAIL(BasicCode.parameters_incorrect); 81 | } 82 | CodeUserQuota codeUserQuota = _codeUserService.getQuota(openId); 83 | 84 | return Return.SUCCESS(BasicCode.success).data(codeUserQuota); 85 | 86 | } 87 | 88 | @PostMapping("/incrQuota") 89 | public Return incrQuota(@RequestBody CodeUserQuota codeUserQuota) { 90 | 91 | if(Strings.isNullOrEmpty(codeUserQuota.getOpenid())){ 92 | return Return.FAIL(BasicCode.parameters_incorrect); 93 | } 94 | int cnt = _codeUserService.incrQuota(codeUserQuota.getOpenid()); 95 | if (cnt > 0) { 96 | return Return.SUCCESS(BasicCode.success); 97 | }else{ 98 | return Return.FAIL(BasicCode.error); 99 | } 100 | 101 | } 102 | 103 | @PostMapping("/setQuota") 104 | public Return setQuota(@RequestBody CodeUserQuota codeUserQuota) { 105 | 106 | if(Strings.isNullOrEmpty(codeUserQuota.getOpenid())){ 107 | return Return.FAIL(BasicCode.parameters_incorrect); 108 | } 109 | int cnt = _codeUserService.saveQuota(codeUserQuota); 110 | if (cnt > 0) { 111 | return Return.SUCCESS(BasicCode.success).data(codeUserQuota); 112 | }else{ 113 | return Return.FAIL(BasicCode.error); 114 | } 115 | } 116 | 117 | @PostMapping("/inputCode") 118 | public Return inputCode(@RequestBody Map params) { 119 | String openId = params.get("openId"); 120 | String code = params.get("code"); 121 | 122 | if(Strings.isNullOrEmpty(openId)){ 123 | return Return.FAIL(BasicCode.parameters_incorrect); 124 | } 125 | return _codeUserService.inputCode(openId,code); 126 | } 127 | 128 | 129 | // 给小程序调用的入口 130 | @PostMapping("/doAsk") 131 | public Return doAsk(@RequestBody Map postQuestion) { 132 | 133 | 134 | if (!postQuestion.containsKey("openId")) { 135 | return Return.FAIL(BasicCode.parameters_incorrect); 136 | } 137 | if (!postQuestion.containsKey("question")) { 138 | return Return.FAIL(BasicCode.parameters_incorrect); 139 | } 140 | 141 | String openId = String.valueOf(postQuestion.get("openId")); 142 | // list 提示词,用于传上下文 143 | Object hint = postQuestion.get("hint"); 144 | // 实际的问题 145 | String question = String.valueOf(postQuestion.get("question")); 146 | 147 | String apikey = String.valueOf(postQuestion.get("apikey")); 148 | 149 | return _codeUserService.doAsk(apikey,openId,hint,question); 150 | } 151 | 152 | 153 | // 3.5 官方接口 154 | @PostMapping("/doRequest") 155 | public Return doRequest(@RequestBody Map postQuestion) { 156 | 157 | if (!postQuestion.containsKey("apikey")) { 158 | return Return.FAIL(BasicCode.parameters_incorrect); 159 | } 160 | if (!postQuestion.containsKey("question")) { 161 | return Return.FAIL(BasicCode.parameters_incorrect); 162 | } 163 | try{ 164 | String apikey = String.valueOf(postQuestion.get("apikey")); 165 | List question = JsonConvert.toObject(JsonConvert.toJson(postQuestion.get("question")), List.class); 166 | Double temperature = 0.2; 167 | if (postQuestion.containsKey("temperature")) { 168 | 169 | temperature = Double.parseDouble(String.valueOf(postQuestion.get("temperature"))); 170 | if(temperature > 1){ 171 | return Return.FAIL(BasicCode.parameters_incorrect); 172 | } 173 | } 174 | return _codeUserService.doRequest(apikey,temperature,question); 175 | // return Return.SUCCESS(BasicCode.success).data("你好"); 176 | }catch(Exception e){ 177 | logger.error(e); 178 | return Return.FAIL(BasicCode.parameters_incorrect); 179 | } 180 | } 181 | // 假接口,用于调试 182 | @PostMapping("/doDummy") 183 | public Return doDummy(@RequestBody Map postQuestion) { 184 | String openId = postQuestion.get("openId"); 185 | String question = postQuestion.get("question"); 186 | String method = postQuestion.get("method"); 187 | 188 | if (Strings.isNullOrEmpty(openId)) { 189 | return Return.FAIL(BasicCode.parameters_incorrect); 190 | } 191 | if (Strings.isNullOrEmpty(question)) { 192 | return Return.FAIL(BasicCode.parameters_incorrect); 193 | } 194 | return Return.SUCCESS(BasicCode.success).data("中所有低于等于500的偶数?\\n\\ndef evenFibonacci(n):\\n result = []\\n # Initialize first two even Fibonacci numbers \\n f1 = 0\\n f2 = 2\\n \\n # Add the first two even numbers to result \\n result.append(f1)\\n result.append(f2)\\n \\n next_even_fib = f1 + f2\\n \\n # Calculate and add remaining even numbers of the \\n # Fibonacci series till n\\n while(next_even_fib <= n):\\n result.append(next_even_fib)\\n next_even_fib = 4 * f2 + f1\\n f1 = f2\\n f2 = next_even_fib\\n \\n # Print all even elements of result\\n print(*result, sep = \\\", \\\")\\n \\n# Driver code\\nn = 500\\nevenFibonacci(n)"); 195 | 196 | } 197 | 198 | } 199 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/Service/CodeUserService.java: -------------------------------------------------------------------------------- 1 | package com.openapi.Service; 2 | 3 | import java.io.IOException; 4 | import java.security.KeyManagementException; 5 | import java.security.NoSuchAlgorithmException; 6 | import java.security.cert.CertificateException; 7 | import java.security.cert.X509Certificate; 8 | import java.util.ArrayList; 9 | import java.util.Arrays; 10 | import java.util.Calendar; 11 | import java.util.Collections; 12 | import java.util.Date; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.concurrent.TimeUnit; 17 | 18 | import org.apache.logging.log4j.LogManager; 19 | import org.apache.logging.log4j.Logger; 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.stereotype.Service; 22 | import org.springframework.transaction.annotation.Transactional; 23 | 24 | import com.google.common.base.Strings; 25 | import com.openapi.Basic.BasicCode; 26 | import com.openapi.Basic.JsonConvert; 27 | import com.openapi.Basic.Return; 28 | import com.openapi.Dao.ChatHistMapper; 29 | import com.openapi.Dao.CodeUserMapper; 30 | import com.openapi.Dao.CodeUserQuotaMapper; 31 | import com.openapi.Dao.InviteCodeMapper; 32 | import com.openapi.Database.TgDataSourceConfig; 33 | import com.openapi.Model.ChatHist; 34 | import com.openapi.Model.CodeUser; 35 | import com.openapi.Model.CodeUserQuota; 36 | import com.openapi.Model.InviteCode; 37 | import com.openapi.tools.OkHttpClientUtil.OkHttpTools; 38 | import com.openapi.tools.SendAlarmTools; 39 | 40 | import javax.net.ssl.SSLContext; 41 | import javax.net.ssl.TrustManager; 42 | import javax.net.ssl.X509TrustManager; 43 | import okhttp3.Headers; 44 | import okhttp3.MediaType; 45 | import okhttp3.OkHttpClient; 46 | import okhttp3.Request; 47 | import okhttp3.RequestBody; 48 | import okhttp3.Response; 49 | 50 | 51 | @Service 52 | public class CodeUserService { 53 | 54 | private static Logger logger = LogManager.getLogger(CodeUserService.class); 55 | 56 | @Autowired 57 | TgDataSourceConfig _tgDataSourceConfig; 58 | 59 | @Autowired 60 | CodeUserMapper _codeUserMapper; 61 | 62 | @Autowired 63 | CodeUserQuotaMapper _codeUserQuotaMapper; 64 | 65 | @Autowired 66 | InviteCodeMapper _inviteCodeMapper; 67 | 68 | @Autowired 69 | ChatHistMapper _chatHistMapper; 70 | 71 | 72 | public int save(CodeUser bizUser){ 73 | 74 | return _codeUserMapper.upsert(bizUser); 75 | } 76 | 77 | public CodeUser getCodeUser(String id){ 78 | CodeUser user = _codeUserMapper.selectById(id); 79 | return user; 80 | } 81 | 82 | public int deleteByOpenId(String openId){ 83 | return _codeUserMapper.deleteByOpenId(openId); 84 | } 85 | 86 | public CodeUser getCodeUserByOpenId(String openId){ 87 | return _codeUserMapper.getCodeUserByOpenId(openId); 88 | } 89 | 90 | public CodeUser getCodeUserByInviteCode(String invitecode){ 91 | return _codeUserMapper.getCodeUserByInviteCode(invitecode); 92 | } 93 | 94 | public CodeUserQuota getQuota(String openId){ 95 | CodeUserQuota quota = _codeUserQuotaMapper.getCodeUserQuotaByOpenId(openId); 96 | if(quota == null){ 97 | // 没有先初始化 98 | quota = new CodeUserQuota(); 99 | quota.setOpenid(openId); 100 | quota.setCnt(1); 101 | quota.setMaxcnt(5); 102 | if(_codeUserQuotaMapper.upsert(quota) > 0){ 103 | return quota; 104 | }else{ 105 | quota.setCnt(9999999); 106 | return quota; 107 | } 108 | }else{ 109 | return _codeUserQuotaMapper.getCodeUserQuotaByOpenId(openId); 110 | } 111 | } 112 | 113 | public int incrQuota(String openId){ 114 | return incrQuota(openId,1); 115 | } 116 | 117 | public int incrQuota(String openId,int addCnt){ 118 | 119 | CodeUserQuota quota = getQuota(openId); 120 | quota.setCnt(quota.getCnt()+addCnt); 121 | quota.setUpdatetime(new Date()); 122 | return _codeUserQuotaMapper.upsert(quota); 123 | } 124 | 125 | public int incrMaxQuota(String openId,int addCnt){ 126 | 127 | CodeUserQuota quota = getQuota(openId); 128 | quota.setMaxcnt(quota.getMaxcnt()+addCnt); 129 | // 不能更新updatetime,避免计算cnt错误 130 | // quota.setUpdatetime(new Date()); 131 | return _codeUserQuotaMapper.upsert(quota); 132 | } 133 | 134 | public int saveQuota(CodeUserQuota quota){ 135 | quota.setUpdatetime(new Date()); 136 | return _codeUserQuotaMapper.upsert(quota); 137 | } 138 | 139 | @Transactional 140 | public Return inputCode(String consumeopenId,String code){ 141 | 142 | 143 | InviteCode iv = _inviteCodeMapper.getByCode(code,consumeopenId); 144 | if (iv !=null) { 145 | // 好友已输入过 146 | return Return.FAIL(BasicCode.data_exist); 147 | } 148 | 149 | CodeUser produceuser = getCodeUserByInviteCode(code); 150 | if(produceuser==null){ 151 | // code不存在 152 | logger.info("code {} 没有user记录" , code); 153 | return Return.FAIL(BasicCode.data_not_found); 154 | } 155 | // 156 | if(consumeopenId.equals(produceuser.getOpenid())){ 157 | logger.info("code {} 不能自己邀请自己" , code); 158 | return Return.FAIL(BasicCode.data_not_found); 159 | } 160 | 161 | CodeUser consumeuser = getCodeUserByOpenId(consumeopenId); 162 | if(consumeuser==null){ 163 | logger.info("openid {} 没有user记录" , consumeopenId); 164 | return Return.FAIL(BasicCode.data_not_found); 165 | } 166 | 167 | //不超过3次 168 | int total = _inviteCodeMapper.count(code); 169 | if(total >=3) { 170 | logger.info("code {} 超过3次" , code); 171 | return Return.FAIL(BasicCode.quota_over_limit); 172 | } 173 | 174 | iv = new InviteCode(); 175 | iv.setCode(code); 176 | iv.setConsumeopenid(consumeopenId); 177 | iv.setProduceopenid(produceuser.getOpenid()); 178 | 179 | int cnt = _inviteCodeMapper.insert(iv); 180 | if(cnt < 0){ 181 | return Return.FAIL(BasicCode.error); 182 | } 183 | 184 | // 双方各加次数 185 | incrMaxQuota(consumeopenId,10); 186 | incrMaxQuota(produceuser.getOpenid(),10); 187 | 188 | return Return.SUCCESS(BasicCode.success); 189 | 190 | } 191 | 192 | public Return doAsk(String apikey ,String openId,Object hint, String question){ 193 | 194 | if(Strings.isNullOrEmpty(apikey) || "null".equals(apikey)){ 195 | apikey = getKey(); 196 | } 197 | 198 | 199 | // Return checkQuotaRet = checkQuota(openId,"api"); 200 | // 201 | // if(!checkQuotaRet.is_success()){ 202 | // return checkQuotaRet; 203 | // } 204 | 205 | try{ 206 | 207 | 208 | Map head = new HashMap(); 209 | Map chatParam = new HashMap(); 210 | chatParam.put("model","gpt-3.5-turbo"); 211 | 212 | List message = new ArrayList(); 213 | if(hint!=null){ 214 | message.add(JsonConvert.toObject(JsonConvert.toJson(hint),List.class)); 215 | } 216 | 217 | Map content = new HashMap(); 218 | content.put("role","user"); 219 | content.put("content",question); 220 | 221 | message.add(content); 222 | 223 | chatParam.put("question",message); 224 | chatParam.put("apikey",apikey); 225 | 226 | logger.info("chatgpt接口参数:{}",chatParam); 227 | 228 | String url = _tgDataSourceConfig.getApiserver().concat("/GPTMGR/aicode/doRequest"); 229 | 230 | 231 | String str = OkHttpTools.post(OkHttpTools.MEDIA_TYPE_JSON,url,chatParam); 232 | 233 | logger.info("api接口返回:{}",str); 234 | 235 | Return ret_resp = JsonConvert.toObject(str,Return.class); 236 | 237 | if(!ret_resp.is_success()){ 238 | if(str.contains("insufficient_quota")){ 239 | logger.error("{} 余额不足",apikey); 240 | SendAlarmTools.sendAlarm(apikey.concat("余额不足")); 241 | } 242 | 243 | ChatHist answer = new ChatHist(); 244 | answer.setOpenid(openId); 245 | answer.setQuestion(JsonConvert.toJson(chatParam)); 246 | answer.setResult("服务负载过高,请稍后再试"); 247 | _chatHistMapper.insert(answer); 248 | }else{ 249 | String text = String.valueOf(ret_resp.get_data()); 250 | 251 | ChatHist answer = new ChatHist(); 252 | answer.setOpenid(openId); 253 | answer.setQuestion(JsonConvert.toJson(chatParam)); 254 | answer.setResult(text); 255 | _chatHistMapper.insert(answer); 256 | return Return.SUCCESS(BasicCode.success).data(text); 257 | } 258 | 259 | 260 | }catch(Exception e) { 261 | e.printStackTrace(); 262 | logger.error("请求异常", openId); 263 | } 264 | return Return.FAIL(BasicCode.error); 265 | } 266 | 267 | public Return doRequest(String apikey,double temperature,List questions){ 268 | 269 | if(Strings.isNullOrEmpty(apikey)){ 270 | logger.info("没有apikey" ); 271 | return Return.FAIL(BasicCode.error); 272 | } 273 | 274 | Map header = new HashMap(); 275 | header.put("authorization","Bearer "+ apikey); 276 | Headers headers = Headers.of(header); 277 | 278 | try{ 279 | String url = "https://api.openai.com/v1/chat/completions"; 280 | OkHttpClient client = getUnsafeOkHttpClient(); 281 | Map chatParam = new HashMap(); 282 | chatParam.put("model","gpt-3.5-turbo"); 283 | 284 | chatParam.put("temperature",temperature); 285 | chatParam.put("messages",questions); 286 | 287 | // 最多只能输出4k字,所以要控制返回的字符数量 288 | chatParam.put("max_tokens",4000); 289 | 290 | // String str_ret = OkHttpTools.sslpost(OkHttpTools.MEDIA_TYPE_JSON, url, JsonConvert.toJson(chatParam), 30, header); 291 | // return Return.SUCCESS(BasicCode.success).data(str_ret); 292 | // 293 | 294 | 295 | String requestBody = JsonConvert.toJson(chatParam); // 请求体,JSON 格式 296 | 297 | MediaType mediaType = MediaType.parse("application/json; charset=utf-8"); // 设置请求体的媒体类型 298 | RequestBody body = RequestBody.create(mediaType,requestBody); // 创建请求体 299 | 300 | 301 | Request request = new Request.Builder() 302 | .url(url) 303 | .headers(headers) 304 | //.header("authorization","Bearer "+ "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") 305 | .post(body) 306 | .build(); 307 | 308 | logger.info("{}的问题:{}",chatParam); 309 | try (Response response = client.newCall(request).execute()) { 310 | String str_res = response.body().string(); 311 | 312 | logger.info("返回:{}",str_res); 313 | Map map_res = JsonConvert.toObject(str_res,Map.class); 314 | if(map_res.containsKey("error")){ 315 | Map errorMsg = JsonConvert.toObject(JsonConvert.toJson(map_res.get("error")), Map.class); 316 | String type = String.valueOf(errorMsg.get("type")); 317 | // TODO 提醒 318 | if("insufficient_quota".equals(type)){ 319 | 320 | } 321 | return Return.FAIL(BasicCode.error).note(type); 322 | }else{ 323 | List choices = JsonConvert.toObject(JsonConvert.toJson(map_res.get("choices")), List.class); 324 | Map message = JsonConvert.toObject(JsonConvert.toJson(choices.get(0)), Map.class); 325 | Map answer = JsonConvert.toObject(JsonConvert.toJson(message.get("message")), Map.class); 326 | String text = String.valueOf(answer.get("content")); 327 | 328 | return Return.SUCCESS(BasicCode.success).data(text); 329 | } 330 | } catch (IOException e) { 331 | e.printStackTrace(); 332 | logger.error("请求异常:{}" , e.getMessage()); 333 | return Return.FAIL(BasicCode.error); 334 | } 335 | }catch(Exception e){ 336 | e.printStackTrace(); 337 | logger.error("请求异常",e); 338 | return Return.FAIL(BasicCode.error); 339 | } 340 | } 341 | 342 | public static long getTodayZeroTimeStamp() { 343 | Calendar calendar = Calendar.getInstance(); 344 | calendar.set(Calendar.HOUR_OF_DAY, 0); 345 | calendar.set(Calendar.MINUTE, 0); 346 | calendar.set(Calendar.SECOND, 0); 347 | calendar.set(Calendar.MILLISECOND, 0); 348 | return calendar.getTimeInMillis(); 349 | } 350 | 351 | private String getKey(){ 352 | String str_keys = _tgDataSourceConfig.getApikey(); 353 | List keys = Arrays.asList(str_keys.split(",")); 354 | Collections.shuffle(keys); 355 | return keys.get(0); 356 | } 357 | 358 | 359 | private static OkHttpClient getUnsafeOkHttpClient() throws NoSuchAlgorithmException, KeyManagementException { 360 | // 创建一个信任所有证书的 TrustManager 361 | final TrustManager[] trustAllCerts = new TrustManager[] { 362 | new X509TrustManager() { 363 | @Override 364 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 365 | } 366 | 367 | @Override 368 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 369 | } 370 | 371 | @Override 372 | public X509Certificate[] getAcceptedIssuers() { 373 | return new X509Certificate[0]; 374 | } 375 | } 376 | }; 377 | 378 | // 创建一个 SSLContext,并指定信任所有证书 379 | SSLContext sslContext = SSLContext.getInstance("SSL"); 380 | sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); 381 | 382 | // 创建一个 OkHttpClient,并指定 SSLContext 383 | OkHttpClient.Builder builder = new OkHttpClient.Builder(); 384 | builder.readTimeout(30, TimeUnit.SECONDS); 385 | builder.connectTimeout(10,TimeUnit.SECONDS); 386 | builder.writeTimeout(30,TimeUnit.SECONDS); 387 | builder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0]); 388 | 389 | return builder.build(); 390 | } 391 | } 392 | -------------------------------------------------------------------------------- /src/main/java/com/openapi/tools/OkHttpClientUtil/OkHttpTools.java: -------------------------------------------------------------------------------- 1 | package com.openapi.tools.OkHttpClientUtil; 2 | 3 | import java.io.IOException; 4 | import java.net.URL; 5 | import java.security.KeyManagementException; 6 | import java.security.NoSuchAlgorithmException; 7 | import java.security.cert.CertificateException; 8 | import java.security.cert.X509Certificate; 9 | import java.util.ArrayList; 10 | import java.util.HashMap; 11 | import java.util.Iterator; 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.concurrent.TimeUnit; 15 | 16 | import org.apache.logging.log4j.LogManager; 17 | import org.apache.logging.log4j.Logger; 18 | 19 | import com.openapi.Basic.JsonConvert; 20 | import com.openapi.Basic.SystemConstant; 21 | 22 | import javax.net.ssl.SSLContext; 23 | import javax.net.ssl.TrustManager; 24 | import javax.net.ssl.X509TrustManager; 25 | import okhttp3.Call; 26 | import okhttp3.Callback; 27 | import okhttp3.ConnectionPool; 28 | import okhttp3.FormBody; 29 | import okhttp3.MediaType; 30 | import okhttp3.MultipartBody; 31 | import okhttp3.OkHttpClient; 32 | import okhttp3.Request; 33 | import okhttp3.RequestBody; 34 | import okhttp3.Response; 35 | import okhttp3.ResponseBody; 36 | 37 | 38 | public class OkHttpTools { 39 | 40 | private static final Logger logger = LogManager.getLogger(OkHttpTools.class); 41 | 42 | private static Integer socket_timeout = 30;// response超时时间 43 | private static Integer connect_timeout = 3;// 连接超时时间 44 | private static Integer maxRequests = 128; // 最大的并发请求数 45 | private static Integer maxRequestsPerHost = 128; //单个主机最大请求并发数 46 | 47 | public static final String MEDIA_TYPE_JSON = "application/json; charset=utf-8"; 48 | public static final String MEDIA_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded; charset=utf-8"; 49 | public static final String MEDIA_TYPE_FORM_DATA = "multipart/form-data; charset=utf-8";// 50 | 51 | private static ArrayList availableMediaType = new ArrayList(); 52 | 53 | private static OkHttpClient.Builder defaultBuilder = 54 | new OkHttpClient.Builder().connectionPool(new ConnectionPool(1, 1, TimeUnit.SECONDS)) 55 | .connectTimeout(connect_timeout, TimeUnit.SECONDS).writeTimeout(socket_timeout, TimeUnit.SECONDS) 56 | .readTimeout(socket_timeout, TimeUnit.SECONDS); 57 | 58 | private static final OkHttpClient zipkinClient = defaultBuilder.build(); 59 | 60 | static { 61 | availableMediaType.add(MEDIA_TYPE_JSON); 62 | availableMediaType.add(MEDIA_TYPE_FORM_URLENCODED); 63 | availableMediaType.add(MEDIA_TYPE_FORM_DATA); 64 | 65 | // zipkinClient.dispatcher().setMaxRequests(maxRequests); 66 | // zipkinClient.dispatcher().setMaxRequestsPerHost(maxRequestsPerHost); 67 | logger.info("初始化HTTP CLIENT"); 68 | } 69 | 70 | //TODO zipkin 71 | private static final Callback default_async_callback = new Callback() { 72 | @Override 73 | public void onFailure(Call call, IOException e) { 74 | logger.error("do_async_get 报错:".concat(call.request().url().toString()), e); 75 | if (!call.isCanceled()) { 76 | call.cancel(); 77 | } 78 | } 79 | 80 | @Override 81 | public void onResponse(Call call, Response response) 82 | throws IOException { 83 | try (ResponseBody responseBody = response.body()) { 84 | if (!response.isSuccessful()) { 85 | throw new IOException(response.request().url() + " Unexpected response: " + response); 86 | } 87 | logger.debug(responseBody.string()); 88 | } 89 | } 90 | }; 91 | 92 | //TODO 添加proxy和cache 93 | //https请求 94 | public static String sslget(String url, Map params, int readTimeoutSeconds, Map header) 95 | throws Exception { 96 | 97 | url = buildURL(url); 98 | 99 | OkHttpClient client = buildClient(readTimeoutSeconds, "1"); 100 | 101 | Request request = buildGetRequest(url, params, header).build(); 102 | 103 | try (Response response = client.newCall(request).execute()) { 104 | return returnRespons(request, response); 105 | } catch (Exception e) { 106 | logger.error("okhttp get error", e); 107 | e.printStackTrace(); 108 | return returnRespons(request, e.getMessage()); 109 | } 110 | } 111 | 112 | //TODO 添加proxy和cache 113 | public static String get(String url, Map params, int readTimeoutSeconds, Map header) 114 | throws Exception { 115 | 116 | url = buildURL(url); 117 | 118 | OkHttpClient client = buildClient(readTimeoutSeconds); 119 | 120 | Request request = buildGetRequest(url, params, header).build(); 121 | 122 | try (Response response = client.newCall(request).execute()) { 123 | 124 | return returnRespons(request, response); 125 | } catch (Exception e) { 126 | logger.error("okhttp get error", e); 127 | e.printStackTrace(); 128 | return returnRespons(request, e.getMessage()); 129 | } 130 | } 131 | 132 | public static String get(String url, Map params) 133 | throws Exception { 134 | return get(url, params, socket_timeout, new HashMap<>()); 135 | } 136 | 137 | public static String get(String url, Map params, int readTimeoutSeconds) 138 | throws Exception { 139 | return get(url, params, readTimeoutSeconds, new HashMap<>() ); 140 | } 141 | 142 | public static void asyncGet(String url, Map params, int readTimeoutSeconds, 143 | Map header, Callback callback, boolean ignoreURLValid) 144 | throws Exception { 145 | url = buildURL(url); 146 | 147 | if (!isTimeOutLegal(readTimeoutSeconds)) { 148 | return; 149 | } 150 | OkHttpClient client = buildClient(readTimeoutSeconds); 151 | 152 | Request request = buildGetRequest(url, params, header).build(); 153 | 154 | if (callback == null) { 155 | client.newCall(request).enqueue(default_async_callback); 156 | } else { 157 | client.newCall(request).enqueue(callback); 158 | } 159 | } 160 | 161 | public static void asyncGet(String url, Map params, Callback callback) 162 | throws Exception { 163 | asyncGet(url, params, socket_timeout, null, callback, false); 164 | } 165 | 166 | public static void asyncGet(String url, Map params, int readTimeoutSeconds, Callback callback) 167 | throws Exception { 168 | asyncGet(url, params, readTimeoutSeconds, null, callback, false); 169 | } 170 | 171 | public static String post(String mediaType, String url, String params) 172 | throws Exception { 173 | return post(mediaType, url, params, 30, null, false); 174 | } 175 | 176 | public static String post(String mediaType, String url, String params, Map header) 177 | throws Exception { 178 | return post(mediaType, url, params, 30, header, false); 179 | } 180 | 181 | public static String sslpost(String mediaType, String url, String params, int readTimeoutSeconds, 182 | Map header) 183 | throws Exception { 184 | 185 | String type = "application/json; charset=utf-8"; 186 | if (mediaType != null && !"".equals(mediaType)) { 187 | type = mediaType; 188 | } 189 | 190 | if (!availableMediaType.contains(type)) { 191 | throw new IOException("Unsupported MediaType: " + mediaType); 192 | } 193 | 194 | url = buildURL(url); 195 | 196 | OkHttpClient client = buildClient(readTimeoutSeconds, "1"); 197 | Request request = buildPostRequest(mediaType, url, params, header).build(); 198 | 199 | try (Response response = client.newCall(request).execute()) { 200 | return returnRespons(request, response); 201 | } catch (Exception e) { 202 | logger.error("okhttp get error", e); 203 | return returnRespons(request, e.getMessage()); 204 | } 205 | } 206 | 207 | public static String post(String mediaType, String url, String params, int readTimeoutSeconds, 208 | Map header, boolean ignoreURLValid) 209 | throws Exception { 210 | 211 | String type = "application/json; charset=utf-8"; 212 | if (mediaType != null && !"".equals(mediaType)) { 213 | type = mediaType; 214 | } 215 | 216 | if (!availableMediaType.contains(type)) { 217 | throw new IOException("Unsupported MediaType: " + mediaType); 218 | } 219 | 220 | url = buildURL(url); 221 | 222 | OkHttpClient client = buildClient(readTimeoutSeconds); 223 | Request request = buildPostRequest(mediaType, url, params, header).build(); 224 | 225 | try (Response response = client.newCall(request).execute()) { 226 | return returnRespons(request, response); 227 | } catch (Exception e) { 228 | logger.error("okhttp get error", e); 229 | return returnRespons(request, e.getMessage()); 230 | } 231 | } 232 | 233 | public static String post(String mediaType, String url, Map params) 234 | throws Exception { 235 | return post(mediaType, url, params, 30, null, false); 236 | } 237 | 238 | public static String post(String mediaType, String url, Map params, Map header) 239 | throws Exception { 240 | return post(mediaType, url, params, 30, header, false); 241 | } 242 | 243 | public static String post(String mediaType, String url, Map params, int readTimeoutSeconds, 244 | Map header, boolean ignoreURLValid) 245 | throws Exception { 246 | 247 | String type = "application/json; charset=utf-8"; 248 | if (mediaType != null && !"".equals(mediaType)) { 249 | type = mediaType; 250 | } 251 | 252 | if (!availableMediaType.contains(type)) { 253 | throw new IOException("Unsupported MediaType: " + mediaType); 254 | } 255 | 256 | url = buildURL(url); 257 | 258 | OkHttpClient client = buildClient(readTimeoutSeconds); 259 | Request request = buildPostRequest(mediaType, url, params, header).build(); 260 | 261 | try (Response response = client.newCall(request).execute()) { 262 | return returnRespons(request, response); 263 | } catch (Exception e) { 264 | return returnRespons(request, e.getMessage()); 265 | } 266 | } 267 | 268 | public static String post(String mediaType, String url, List params) 269 | throws Exception { 270 | return post(mediaType, url, params, 30, null, false); 271 | } 272 | 273 | public static String post(String mediaType, String url, List params, Map header) 274 | throws Exception { 275 | return post(mediaType, url, params, 30, header, false); 276 | } 277 | 278 | public static String post(String mediaType, String url, List params, int readTimeoutSeconds, 279 | Map header, boolean ignoreURLValid) 280 | throws Exception { 281 | 282 | String type = "application/json; charset=utf-8"; 283 | if (mediaType != null && !"".equals(mediaType)) { 284 | type = mediaType; 285 | } 286 | 287 | if (!availableMediaType.contains(type)) { 288 | throw new IOException("Unsupported MediaType: " + mediaType); 289 | } 290 | 291 | url = buildURL(url); 292 | 293 | OkHttpClient client = buildClient(readTimeoutSeconds); 294 | Request request = buildPostRequest(mediaType, url, params, header).build(); 295 | 296 | try (Response response = client.newCall(request).execute()) { 297 | return returnRespons(request, response); 298 | } catch (Exception e) { 299 | e.printStackTrace(); 300 | throw e; 301 | } 302 | } 303 | 304 | public static void asyncPost(String mediaType, String url, Map params, int readTimeoutSeconds, 305 | Map header, Callback callback, boolean ignoreURLValid) 306 | throws Exception { 307 | 308 | String type = "application/json; charset=utf-8"; 309 | if (mediaType != null && !"".equals(mediaType)) { 310 | type = mediaType; 311 | } 312 | 313 | if (!availableMediaType.contains(type)) { 314 | throw new IOException("Unsupported MediaType: " + mediaType); 315 | } 316 | 317 | url = buildURL(url); 318 | 319 | OkHttpClient client = buildClient(readTimeoutSeconds); 320 | Request request = buildPostRequest(mediaType, url, params, header).build(); 321 | 322 | if (callback == null) { 323 | client.newCall(request).enqueue(default_async_callback); 324 | } else { 325 | client.newCall(request).enqueue(callback); 326 | } 327 | } 328 | 329 | //处理response的body 330 | private static String returnRespons(Request request, Response response) 331 | throws Exception { 332 | if (!response.isSuccessful()) { 333 | logger.error(request.url() + " returnRespons" + response); 334 | throw new IOException("Unexpected code: " + response); 335 | } 336 | //TODO 判断body大小是否大于1M 337 | return response.body().string(); 338 | } 339 | 340 | //处理response的body 341 | private static String returnRespons(Request request, String e) 342 | throws Exception { 343 | 344 | logger.error(request.url() + " return Respons:" + e); 345 | throw new IOException("Unexpected code: " + e); 346 | } 347 | 348 | 349 | 350 | private static String buildURL(String url) 351 | throws Exception { 352 | 353 | if (!url.startsWith("http://") && !url.startsWith("https://")) { 354 | url = "http://".concat(url); 355 | } 356 | return url; 357 | } 358 | 359 | //检查超时参数 360 | private static boolean isTimeOutLegal(int readTimeoutSeconds) { 361 | if (readTimeoutSeconds <= 0) { 362 | logger.error("ReadTimeout:" + readTimeoutSeconds + "不正确"); 363 | return false; 364 | } 365 | return true; 366 | } 367 | 368 | private static OkHttpClient getUnsafeOkHttpClient() throws NoSuchAlgorithmException, KeyManagementException { 369 | // 创建一个信任所有证书的 TrustManager 370 | final TrustManager[] trustAllCerts = new TrustManager[] { 371 | new X509TrustManager() { 372 | @Override 373 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 374 | } 375 | 376 | @Override 377 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 378 | } 379 | 380 | @Override 381 | public X509Certificate[] getAcceptedIssuers() { 382 | return new X509Certificate[0]; 383 | } 384 | } 385 | }; 386 | 387 | // 创建一个 SSLContext,并指定信任所有证书 388 | SSLContext sslContext = SSLContext.getInstance("SSL"); 389 | sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); 390 | 391 | // 创建一个 OkHttpClient,并指定 SSLContext 392 | OkHttpClient.Builder builder = new OkHttpClient.Builder(); 393 | builder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0]); 394 | 395 | return builder.build(); 396 | } 397 | public static OkHttpClient buildClient(int readTimeoutSeconds, String str_cert) { 398 | if("1".equals(str_cert)) { 399 | try{ 400 | return getUnsafeOkHttpClient(); 401 | }catch(Exception e){ 402 | e.printStackTrace(); 403 | } 404 | }else{ 405 | return zipkinClient; 406 | } 407 | 408 | if (readTimeoutSeconds != socket_timeout) { 409 | 410 | if (str_cert != null && str_cert.length() > 0) { 411 | try { 412 | X509TrustManager x509TrustManager = SSLSocketClient.trustManagerForCertificates(str_cert); 413 | return defaultBuilder.writeTimeout(readTimeoutSeconds, TimeUnit.SECONDS) 414 | .readTimeout(readTimeoutSeconds, TimeUnit.SECONDS) 415 | .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), x509TrustManager).build(); 416 | } catch (Exception e) { 417 | logger.error("trustManager异常", e); 418 | } 419 | } 420 | return defaultBuilder.writeTimeout(readTimeoutSeconds, TimeUnit.SECONDS) 421 | .readTimeout(readTimeoutSeconds, TimeUnit.SECONDS).build(); 422 | } else { 423 | return zipkinClient; 424 | } 425 | } 426 | 427 | private static OkHttpClient buildClient(int readTimeoutSeconds) { 428 | return buildClient(readTimeoutSeconds, null); 429 | } 430 | 431 | private static Request.Builder buildGetRequest(String url, Map param, Map header) { 432 | Request.Builder rqBuilder = new Request.Builder(); 433 | if (param == null) { 434 | param = new HashMap<>(); 435 | } 436 | url = concat_url_params(url, param); 437 | rqBuilder.url(url); 438 | try { 439 | 440 | addHeaders(rqBuilder, new URL(url).getPath(), header, String.valueOf(param.getOrDefault(SystemConstant.accessToken, ""))); 441 | } catch (Exception e) { 442 | addHeaders(rqBuilder, header, String.valueOf(param.getOrDefault(SystemConstant.accessToken, ""))); 443 | } 444 | 445 | return rqBuilder; 446 | } 447 | 448 | 449 | public static Request.Builder buildPostRequest(String mediaType, String url, Object params, 450 | Map header) { 451 | Request.Builder rqBuilder = new Request.Builder(); 452 | rqBuilder.url(url); 453 | 454 | try { 455 | addHeaders(rqBuilder, new URL(url).getPath(), header, ""); 456 | } catch (Exception e) { 457 | addHeaders(rqBuilder, header, ""); 458 | } 459 | 460 | switch (mediaType) { 461 | default: 462 | if (params instanceof String) { 463 | rqBuilder.post(RequestBody.create(MediaType.parse(MEDIA_TYPE_JSON), String.valueOf(params))); 464 | } else { 465 | rqBuilder.post(RequestBody.create(MediaType.parse(MEDIA_TYPE_JSON), JsonConvert.toJson(params))); 466 | } 467 | 468 | break; 469 | case MEDIA_TYPE_FORM_DATA: 470 | MultipartBody.Builder multipartBuilder = new MultipartBody.Builder(); 471 | multipartBuilder.setType(MultipartBody.FORM); 472 | if (params instanceof Map) { 473 | try { 474 | Map p = JsonConvert.toObject(JsonConvert.toJson(params), Map.class); 475 | if (p.isEmpty()) { 476 | multipartBuilder.addFormDataPart("", ""); 477 | } 478 | for (String key : p.keySet()) { 479 | multipartBuilder.addFormDataPart(key, p.get(key)); 480 | } 481 | } catch (Exception e) { 482 | e.printStackTrace(); 483 | } 484 | } 485 | RequestBody requestBody = multipartBuilder.build(); 486 | 487 | rqBuilder.post(requestBody); 488 | 489 | break; 490 | case MEDIA_TYPE_FORM_URLENCODED: 491 | FormBody.Builder formBodyBuilder = new FormBody.Builder(); 492 | if (params instanceof Map) { 493 | try { 494 | Map p = JsonConvert.toObject(JsonConvert.toJson(params), Map.class); 495 | for (Map.Entry entry : p.entrySet()) { 496 | formBodyBuilder.add(entry.getKey(), entry.getValue()); 497 | } 498 | } catch (Exception e) { 499 | e.printStackTrace(); 500 | } 501 | 502 | FormBody formBody = formBodyBuilder.build(); 503 | rqBuilder.post(formBody); 504 | } 505 | break; 506 | } 507 | 508 | return rqBuilder; 509 | } 510 | 511 | public static String concat_url_params(String url, Map params) { 512 | 513 | if (params == null || params.isEmpty()) { 514 | return url; 515 | } 516 | Iterator iterator = params.keySet().iterator(); 517 | StringBuilder do_get_sbf = new StringBuilder(); 518 | 519 | String first_key = iterator.next(); 520 | do_get_sbf.append(url).append("?").append(first_key).append("=").append(params.get(first_key)); 521 | while (iterator.hasNext()) { 522 | String key = iterator.next(); 523 | do_get_sbf.append("&").append(key).append("=").append(params.get(key)); 524 | } 525 | url = do_get_sbf.toString(); 526 | return url; 527 | } 528 | 529 | private static void addHeaders(Request.Builder builder, Map headers, String accessToken) { 530 | addHeaders(builder, "", headers, accessToken); 531 | } 532 | 533 | private static void addHeaders(Request.Builder builder, String path, Map headers, String accessToken) { 534 | 535 | if (headers == null || headers.isEmpty()) { 536 | headers = new HashMap<>(); 537 | } 538 | 539 | headers.put("Connection", "close"); 540 | 541 | headers.forEach((key, value) -> { 542 | if (value != null) { 543 | builder.header(key, value); 544 | } 545 | }); 546 | } 547 | } 548 | --------------------------------------------------------------------------------