1:一个生成随机字符串的方法
// length用户要求产生字符串的长度 public static String getRandomString(int length) { String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); }
2:一个生成sign并放入map的方法(CONFIG=应用密匙)
public static Map<String, Object> getSignature(Map<String, Object> params, String CONFIG) throws IOException { Map<String, Object> sortedParams = new TreeMap<>(params); Set<Map.Entry<String, Object>> entrys = sortedParams.entrySet(); StringBuilder baseString = new StringBuilder(); for (Map.Entry<String, Object> param : entrys) { if (param.getValue() != null && !"".equals(param.getKey().trim()) && !"sign".equals(param.getKey().trim()) && !"".equals(param.getValue())) { baseString .append(param.getKey().trim()) .append("=") .append(URLEncoder.encode(param.getValue().toString(), "UTF-8")) .append("&"); } } if (baseString.length() > 0) { baseString.deleteCharAt(baseString.length() - 1).append("&app_key=").append(CONFIG); } try { String sign = MD5Utils.getMD5String(baseString.toString()); System.out.println("sign:" + sign.toUpperCase()); sortedParams.put("sign", sign); } catch (Exception ex) { throw new IOException(ex); } return sortedParams; }
3:一个将map生成key=value&key2=value2的方法
public static String paramToStrNotEncode(Map<String, Object> params) throws UnsupportedEncodingException { StringBuffer content = new StringBuffer(); if (params.isEmpty()) params.put("_NULL", "NULL"); // 补空 int i = 0; for (Map.Entry<String, Object> entry : params.entrySet()) { String key = entry.getKey(); String value = entry.getValue() == null ? "" : entry.getValue().toString(); value = URLEncoder.encode(value, UTF8); content.append((i == 0 ? "" : "&") + key + "=" + value); i++; } return content.toString(); }
4:一个post方法
public static String post(String urlStr, String body) { String response = ""; HttpURLConnection conn = null; try { URL url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Charset", "utf-8"); conn.setReadTimeout(connect_timeout); conn.setConnectTimeout(connect_timeout); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); conn.getOutputStream().write(body.getBytes("UTF-8")); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); StringBuffer buffer = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { buffer.append(line); } response = buffer.toString(); in.close(); } catch (IOException e) { log.error("", e); } finally { if (conn != null) conn.disconnect(); } return response; }
准备就绪
private static final int APPID = ; private static final String KEY = ""; private static final String URL = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat"; public static String chat(String content) { String result = ""; int time_stamp = (int) (new Date().getTime() / 1000); String nonce_str = CommonUtil.getRandomString(16); try { Map<String, Object> map = new HashMap<>(); map.put("app_id", APPID); map.put("time_stamp", time_stamp); map.put("nonce_str", nonce_str); map.put("session", 10000); map.put("question", content); map = CommonUtil.getSignature(map, KEY); String body = HttpUtil.paramToStrNotEncode(map); String conten = HttpUtil.post(URL, body); JSONObject json = JSONObject.parseObject(conten); if (json.getIntValue("ret") == 0) { JSONObject data = json.getJSONObject("data"); result = data.getString("answer"); } log.info("聊天信息:{}", conten); } catch (Exception e) { result = "聊天出状况啦,待会再试!"; } result += "(回复\"帮助\"查看我有哪些功能吧)"; return result; }