anderx лет назад: 2
Родитель
Сommit
6c59633924

+ 2 - 2
src/main/java/com/goafanti/baiduAI/BaiduChatErrorEnums.java

@@ -19,8 +19,8 @@ public enum BaiduChatErrorEnums {
     MAXER(17,"每天请求量超限额"),
     QPSER(18,"QPS超限额"),
     TKCXWX(19,"无效的access_token参数"),
-    TKWX(100,"access_token无效"),
-    TKGQ(110,"access token过期"),
+    TKWX(100,"access_token验证无效"),
+    TKGQ(110,"access token验证过期"),
     FWQNCW(111,"服务内部错误。"),
     RCER(336000,"入参格式有误"),
     BODYER(336002,"入参body不是标准的JSON格式。"),

+ 38 - 55
src/main/java/com/goafanti/common/utils/BaiduChatUtils.java

@@ -6,18 +6,11 @@ import com.goafanti.baiduAI.BaiduChatErrorEnums;
 import com.goafanti.baiduAI.bo.*;
 import com.goafanti.common.error.BusinessException;
 import okhttp3.*;
-import org.apache.http.client.ClientProtocolException;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.scheduling.annotation.Async;
-import org.springframework.stereotype.Component;
-import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
-import retrofit2.http.GET;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
+
+import java.io.*;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.ProtocolException;
@@ -25,7 +18,6 @@ import java.net.URL;
 import java.nio.charset.StandardCharsets;
 import java.util.Calendar;
 import java.util.HashMap;
-import java.util.Map;
 import java.util.concurrent.TimeUnit;
 
 
@@ -52,45 +44,12 @@ public class BaiduChatUtils {
             .build();
 
 
-
-    public  String  getBaiduAccessToken() throws IOException {
-        MediaType mediaType = MediaType.parse("application/json");
-        RequestBody body = RequestBody.create(mediaType, "");
-        StringBuffer url= new StringBuffer(BAIDU_ACCESSTOKEN_URL)
-                .append("client_id=").append(baiduApiKey).append("&client_secret=").append(baiduSecretKey);
-        Request request = new Request.Builder()
-                .url(url.toString())
-                .method("POST", body)
-                .addHeader("Content-Type", "application/json")
-                .addHeader("Accept", "application/json")
-                .build();
-        Response response = HTTP_CLIENT.newCall(request).execute();
-        String result=response.body().string();
-        HashMap<String,Object> map = JSON.parseObject(result, HashMap.class);
-        String  accessToken = map.get("access_token").toString();
-        LoggerUtils.debug(getClass(),"获取accessToken="+accessToken);
-        return accessToken;
-    }
-
-    public  String sendBaiduAI(InputSendChat in) throws IOException{
-        String accessToken = getRedisBaiduAccessToken();
-        MediaType mediaType = MediaType.parse("application/json");
-        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(in));
-        Request request = new Request.Builder()
-                .url(BAIDU_CHAT_WXYY_URL + accessToken)
-                .method("POST", body)
-                .addHeader("Content-Type", "application/json")
-                .build();
-        Response response = HTTP_CLIENT.newCall(request).execute();
-        String result=response.body().string();
-        return result;
-    }
-
     @Async
     public void sendBaiduAiStream(InputSendChat inputSendChat) throws IOException {
         SseResult res = null;
         BufferedReader reader=null;
         InputStreamReader inputStreamReader=null;
+        OutputStream outputStream=null;
         try {
             String baidu_url=BAIDU_CHAT_WXYY_URL+getRedisBaiduAccessToken();
             URL url = new URL(baidu_url);
@@ -104,31 +63,30 @@ public class BaiduChatUtils {
             String requestBody=JSON.toJSONString(inputSendChat);
             byte[] postData = requestBody.getBytes(StandardCharsets.UTF_8);
             connection.setRequestProperty("Content-Length", String.valueOf(postData.length));
-            connection.getOutputStream().write(postData);
+            outputStream =connection.getOutputStream();
+            outputStream.write(postData);
             InputStream responseStream = connection.getInputStream();
             inputStreamReader = new InputStreamReader(responseStream, "UTF-8");
             reader = new BufferedReader(inputStreamReader);
             String line;
-             res =  SseMap.sseEmitterMap.get(inputSendChat.getUserId());
+            res =  SseMap.sseEmitterMap.get(inputSendChat.getUserId());
             while ((line = reader.readLine())!= null) {
                 // 每行数据中以 "data:" 开头的部分即为实际的响应数据
                 if (StringUtils.isNotBlank(line)){
-                    System.out.println(line);
                     if (line.startsWith("data:")) {
                         String data = line.substring("data:".length()).trim();
                         JSONObject jsonObject = JSONObject.parseObject(data);
                         Boolean isEnd = jsonObject.getBoolean("is_end");
-//                  OutSendChatOK out =jsonObject.toJavaObject(OutSendChatOK.class);
-//                    System.out.println(data);
                         res.sseEmitter.send(data);
                         if(isEnd){
                             break;
                         }
+                        //错误返回格式{"error_code":110,"error_msg":"Access token invalid or no longer valid"}
                     }else if(line.startsWith("{")) {
                         JSONObject jsonObject = JSONObject.parseObject(line);
                         Integer errorCode = jsonObject.getInteger("error_code");
+                        OutChatER out=new OutChatER();
                         if (errorCode!=null){
-                            OutChatER out=new OutChatER();
                             out.setError_code(errorCode);
                             if (errorCode.equals("336003")){
                                 out.setError_msg(BaiduChatErrorEnums.BycodeGetMsg(errorCode)+jsonObject.getString("error_msg"));
@@ -136,11 +94,12 @@ public class BaiduChatUtils {
                                 out.setError_msg(BaiduChatErrorEnums.BycodeGetMsg(errorCode));
                             }
                         }
-                        res.sseEmitter.send(JSON.toJSONString(errorCode));
+                        String errorStr=JSON.toJSONString(out);
+                        LoggerUtils.debug(getClass(),errorStr);
+                        res.sseEmitter.send(errorStr);
                     }
                 }
             }
-
             res.sseEmitter.complete();
         } catch (MalformedURLException e) {
             e.printStackTrace();
@@ -151,6 +110,7 @@ public class BaiduChatUtils {
             LoggerUtils.debug(getClass(),"前端网页已关闭");
         }finally {
             inputStreamReader.close();
+            outputStream.close();
             reader.close();
             res.sseEmitter.complete();
             SseMap.sseEmitterMap.remove(inputSendChat.getUserId());
@@ -159,6 +119,31 @@ public class BaiduChatUtils {
     }
 
 
+
+
+    public  String  getBaiduAccessToken() throws IOException {
+        MediaType mediaType = MediaType.parse("application/json");
+        RequestBody body = RequestBody.create(mediaType, "");
+        StringBuffer url= new StringBuffer(BAIDU_ACCESSTOKEN_URL)
+                .append("client_id=").append(baiduApiKey).append("&client_secret=").append(baiduSecretKey);
+        Request request = new Request.Builder()
+                .url(url.toString())
+                .method("POST", body)
+                .addHeader("Content-Type", "application/json")
+                .addHeader("Accept", "application/json")
+                .build();
+        Response response = HTTP_CLIENT.newCall(request).execute();
+        String result=response.body().string();
+        HashMap<String,Object> map = JSON.parseObject(result, HashMap.class);
+        String  accessToken = map.get("access_token").toString();
+        LoggerUtils.debug(getClass(),"获取accessToken="+accessToken);
+        return accessToken;
+    }
+
+
+
+
+
     private void sendJitaoBaiWen(String userId, String s) throws IOException {
         SseResult res =  SseMap.sseEmitterMap.get(userId);
         res.sseEmitter.send(s);
@@ -166,9 +151,8 @@ public class BaiduChatUtils {
 
 
     private String  getRedisBaiduAccessToken() {
-        String redisAccessToken=null;
+        String redisAccessToken;
         String redisTime=redisUtil.getString("baiduAccessTime");
-        //没有
         if (redisTime !=null){
             Calendar cal = Calendar.getInstance();
             Long redisAccessTime=Long.valueOf(redisTime);
@@ -179,7 +163,6 @@ public class BaiduChatUtils {
                 LoggerUtils.debug(getClass(),"accessToken过期,重新获取!");
             }else {
                 redisAccessToken=  redisUtil.getString("baiduAccessToken");
-                LoggerUtils.debug(getClass(),"accessToken从redis获取成功!");
             }
         }else {
             redisAccessToken=pushRedisBaiduAccessToken();

+ 12 - 6
src/main/java/com/goafanti/common/utils/DateUtils.java

@@ -20,7 +20,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 	/**
 	 * Determines how two dates compare up to no more than the specified most
 	 * significant field.
-	 * 
+	 *
 	 * @param date1
 	 *            the first date, not <code>null</code>
 	 * @param date2
@@ -45,7 +45,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 	/**
 	 * Determines how two dates compare up to no more than the specified most
 	 * significant field.
-	 * 
+	 *
 	 * @param date1
 	 *            the first date, not <code>null</code>
 	 * @param date2
@@ -66,7 +66,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 	/**
 	 * Determines how two dates compare up to no more than the specified most
 	 * significant field.
-	 * 
+	 *
 	 * @param date1
 	 *            the first date, not <code>null</code>
 	 * @param date2
@@ -386,7 +386,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 		return calendar.getTime();
 	}
 
-	/** 
+	/**
 	 *  返回前一年最后一天
 	 * @param date
 	 * @return
@@ -420,12 +420,18 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 		return format.format(date);
 	}
 
+	public static String formatDate(Calendar calendar, String pattern) {
+		Date date=calendar.getTime();
+		SimpleDateFormat format = new SimpleDateFormat(pattern);
+		return format.format(date);
+	}
+
 	/**
 	 * 解析日期
 	 * @param source
 	 * @param pattern
 	 * @return
-	 * @throws ParseException 
+	 * @throws ParseException
 	 */
 	public static Date parseDate(String source, String pattern) throws ParseException {
 		SimpleDateFormat format = new SimpleDateFormat(pattern);
@@ -460,7 +466,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 		ca.setTime(date);
 		ca.add(Calendar.DATE, a);
 		return ca.getTime();
-		
+
 	}
 
 }

+ 9 - 8
src/main/webapp/WEB-INF/views/portal/answers.html

@@ -23,14 +23,7 @@
       <div>助您高效获取科研领域专业信息</div>
     </div>
   </div>
-  <div class="basic_content">
-    <div class="basic_bottom">
-      <textarea id="textarea" placeholder="在这里输入问题..." size="large" maxlength="500" class="ant-input"></textarea>
-      <button type="button" class="ant-but">
-        <img th:src="${portalHost + '/img/send.svg'}">
-      </button>
-    </div>
-  </div>
+
   <div class="contentCenter">
     <div class="basic_list" >
       <div class="basic_ltit">
@@ -46,6 +39,14 @@
     </div>
   </div>
 </div>
+<div class="basic_content">
+  <div class="basic_bottom">
+    <textarea id="textarea" placeholder="在这里输入问题..." size="large" maxlength="500" class="ant-input"></textarea>
+    <button type="button" class="ant-but">
+      <img th:src="${portalHost + '/img/send.svg'}">
+    </button>
+  </div>
+</div>
 <div class="smg"><input type="text" name="msg" value="" id="msg" /></div>
 <!-- 中间内容结束 -->
 <!--<footer>-->