Java调用腾讯AI智能聊天服务的方法

本文章只做个人记录使用,有需要可以参考,不明白下方留言

直接上代码,首先,传过来你要发送的消息

 

TencentAIAnswer 实体类

import java.io.Serializable;

/**
 * 收到的微信消息
 * 
 * @date 创建时间:2017年7月3日 下午10:28:06
 * @version 1.0
 *
 */
public class TencentAIAnswer implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String session;
	private String answer;

	public String getSession() {
		return session;
	}

	public void setSession(String session) {
		this.session = session;
	}

	public String getAnswer() {
		return answer;
	}

	public void setAnswer(String answer) {
		this.answer = answer;
	}

}

RandomUtils 工具类

import java.util.Random;

public class RandomUtils {
	public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	public static final String LETTERCHAR = "abcdefghijkllmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	public static final String NUMBERCHAR = "0123456789";
	public static final int[] NUMBERCHARARR = { 1, 2, 3, 4, 5, 6, 7 };

	/**
	 * 返回一个定长的随机字符串(只包含大小写字母、数字)
	 * 
	 * @param length 随机字符串长度
	 * @return 随机字符串
	 */
	public static String generateString(int length) {
		StringBuffer sb = new StringBuffer();
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
		}
		return sb.toString();
	}

	/**
	 * 返回一个定长的随机纯字母字符串(只包含大小写字母)
	 * 
	 * @param length 随机字符串长度
	 * @return 随机字符串
	 */
	public static String generateMixString(int length) {
		StringBuffer sb = new StringBuffer();
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			sb.append(ALLCHAR.charAt(random.nextInt(LETTERCHAR.length())));
		}
		return sb.toString();
	}

	/**
	 * 返回一个定长的随机纯大写字母字符串(只包含大小写字母)
	 * 
	 * @param length 随机字符串长度
	 * @return 随机字符串
	 */
	public static String generateLowerString(int length) {
		return generateMixString(length).toLowerCase();
	}

	/**
	 * 返回一个定长的随机纯小写字母字符串(只包含大小写字母)
	 * 
	 * @param length 随机字符串长度
	 * @return 随机字符串
	 */
	public static String generateUpperString(int length) {
		return generateMixString(length).toUpperCase();
	}

	/**
	 * 生成一个定长的纯0字符串
	 * 
	 * @param length 字符串长度
	 * @return 纯0字符串
	 */
	public static String generateZeroString(int length) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			sb.append('0');
		}
		return sb.toString();
	}

	/**
	 * 根据数字生成一个定长的字符串,长度不够前面补0
	 * 
	 * @param num       数字
	 * @param fixdlenth 字符串长度
	 * @return 定长的字符串
	 */
	public static String toFixdLengthString(long num, int fixdlenth) {
		StringBuffer sb = new StringBuffer();
		String strNum = String.valueOf(num);
		if (fixdlenth - strNum.length() >= 0) {
			sb.append(generateZeroString(fixdlenth - strNum.length()));
		} else {
			throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!");
		}
		sb.append(strNum);
		return sb.toString();
	}

	/**
	 * 每次生成的len位数都不相同
	 * 
	 * @param param
	 * @return 定长的数字
	 */
	public static int getNotSimple(int len) {
		Random rand = new Random();
		for (int i = NUMBERCHARARR.length; i > 1; i--) {
			int index = rand.nextInt(i);
			int tmp = NUMBERCHARARR[index];
			NUMBERCHARARR[index] = NUMBERCHARARR[i - 1];
			NUMBERCHARARR[i - 1] = tmp;
		}
		int result = 0;
		for (int i = 0; i < len; i++) {
			result = result * 10 + NUMBERCHARARR[i];
		}
		return result;
	}

	public static void main(String[] args) {
		System.out.println("返回一个定长的随机字符串(只包含大小写字母、数字):" + generateString(10));
		System.out.println("返回一个定长的随机纯字母字符串(只包含大小写字母):" + generateMixString(10));
		System.out.println("返回一个定长的随机纯大写字母字符串(只包含大小写字母):" + generateLowerString(10));
		System.out.println("返回一个定长的随机纯小写字母字符串(只包含大小写字母):" + generateUpperString(10));
		System.out.println("生成一个定长的纯0字符串:" + generateZeroString(10));
		System.out.println("根据数字生成一个定长的字符串,长度不够前面补0:" + toFixdLengthString(123, 10));
		System.out.println("每次生成的len位数都不相同:" + getNotSimple(6));
	}
}
public static String getAiAnswer(String msg) {
		String result = null;
		Map tempParamS = new HashMap<>();
		Map signMap;
		try {
			tempParamS.put("app_id", app_id);
			tempParamS.put("time_stamp", new Date().getTime() / 1000 + "");
			tempParamS.put("nonce_str", RandomUtils.generateString(16));
			tempParamS.put("session", RandomUtils.getNotSimple(6) + "");
			tempParamS.put("question", msg);
			tempParamS.put("sign", "");
			signMap = Sign.getSignature(tempParamS, app_key);
			String rel = HttpsPostUtil.doPost(url, signMap, "UTF-8");
			if (StringUtils.isNotBlank(rel)) {
				JSONObject obj = JSON.parseObject(rel);
				if (0 == obj.getInteger("ret")) {
					TencentAIAnswer objRet = obj.parseObject(obj.getString("data"), TencentAIAnswer.class);
					result = objRet.getAnswer();
				}
				if (obj.getInteger("ret") < 0) {
					result = "网络异常~";
				}
				if (obj.getInteger("ret") > 0) {
					result = "我脑子被麻花藤玩坏了哦,快找我爸爸韩梅梅帮我看看吧~";
				}
			} else {
				result = "我病了,现在不能回答你任何问题哦~";
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

获得签名的方法实现

public static Map getSignature(Map params, String CONFIG) throws IOException {
		Map sortedParams = new TreeMap<>(params);
		Set> entrys = sortedParams.entrySet();
		StringBuilder baseString = new StringBuilder();
		for (Map.Entry 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());
			sortedParams.put("sign", sign);
		} catch (Exception ex) {
			throw new IOException(ex);
		}
		return sortedParams;
	}

下面是POST请求的实现,要注意这个地方是https的请求,所以我们要先封装SSL类以便略过证书的检查

public class SSLClient extends DefaultHttpClient {
	// 用于进行Https请求的HttpClient
	public SSLClient() throws Exception {
		super();
		SSLContext ctx = SSLContext.getInstance("TLS");
		X509TrustManager tm = new X509TrustManager() {
			@Override
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}

			@Override
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		ctx.init(null, new TrustManager[] { tm }, null);
		SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		ClientConnectionManager ccm = this.getConnectionManager();
		SchemeRegistry sr = ccm.getSchemeRegistry();
		sr.register(new Scheme("https", 443, ssf));
	}

下面是POST请求实现

public static String doPost(String url, Map map, String charset) {
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		try {
			httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			// 设置参数
			List list = new ArrayList();
			Iterator iterator = map.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry elem = (Entry) iterator.next();
				list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
			}
			if (list.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
				httpPost.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

这样就完成了,写的简单点,不是因为别的,就是因为我太懒

你可能感兴趣的:(JAVA)