Java微信公众号开发(二)—— 百度翻译API

1  百度翻译API

1.1  百度API简介

使用步骤见百度翻译API。该网站也可下载demo代码,但是可能存在一些错误,需修改。

修改后的代码见附件或Eclipse源码。

需要开发者账号、密码。只要审核通过即可。

注意:每月翻译字符数低于200万,享免费服务。超出则收取相应费用。

1.2  百度API程序

 1 import java.io.UnsupportedEncodingException;
 2 import com.baidu.translate.demo.TransApi;
 3 public class Main {
 4     // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
 5     private static final String APP_ID = "20170709000063735";
 6     private static final String SECURITY_KEY = "EiXpUVJAu4mLYinEqgzN";
 7     public static void main(String[] args) throws UnsupportedEncodingException {
 8         TransApi api = new TransApi(APP_ID, SECURITY_KEY);
 9         String query = "中国";
10         System.out.println(api.getTransResult(query, "auto", "en"));
11     }
12 }

主类如上,副类代码一般不修改,直接调用即可。

运行结果(json格式):

{"from":"zh","to":"en","trans_result":[{"src":"u4e2du56fd","dst":"Chinese"}]}

从中提取出我们真正需要的字符串。

2  字符串转算术表达式

JDK1.6以上版本自带的类可以实现调用JS的功能,可以实现执行字符串中的运算公式的功能。

 1 public class runString {
 2     static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
 3     public static void main(String[] args) {
 4         String strs = "1+1*2+(10-(2*(5-3)*(2-1))-4)+10/(5-0)";
 5         try {
 6             System.out.println(jse.eval(strs));
 7         } catch (Exception t) {
 8         }
 9     }
10 }

需要注意:字符串中的括号必须是英文括号,否则会出错。

3  微信公众号后台程序更改

3.1  程序更改

 1 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 2     
 3     req.setCharacterEncoding("UTF-8");//转换编码方式
 4     resp.setCharacterEncoding("UTF-8");
 5     PrintWriter out = resp.getWriter();//通过PrintWriter返回消息至微信后台
 6     
 7     //接收消息
 8     try {
 9         Map<String,String> map = MessageUtil.xmlToMap(req);
10         String fromUserName = map.get("FromUserName");//发送方帐号(一个OpenID)
11         String toUserName = map.get("ToUserName");//开发者微信号
12         String msgType = map.get("MsgType");//text//如果是文本消息的话,MsgType="text"
13         String content = map.get("Content");//文本消息内容
14         
15         String message = null;
16         //判断是否为文本消息
17         if("text".equals(msgType)) {
18             //如果是前缀是回复,则返回使用者的话
19             if(content.startsWith("回复:")) {
20                 com.po.TextMessage text = new com.po.TextMessage();
21                 text.setFromUserName(toUserName);//注意,这里发送者与接收者调换了
22                 text.setToUserName(fromUserName);
23                 text.setMsgType("text");//文本类型
24                 text.setCreateTime("" + new Date().getTime());//当前时间
25                 text.setContent("您发送的消息是:" + content.substring(3));//返回消息。注:从第一个分号开始截取
26                 //将文本消息转换为xml
27                 message = MessageUtil.textMessageToXml(text);
28                 
29                 System.out.println(message);
30             }
31             //如果前缀是翻译,则返回使用者翻译后的话
32             if(content.startsWith("翻译:")) {
33                 //1.先翻译
34                 final String APP_ID = "20170709000063735";//账号
35                 final String SECURITY_KEY = "EiXpUVJAu4mLYinEqgzN";//密码
36                 com.baidu.translate.TransApi api = new com.baidu.translate.TransApi(APP_ID, SECURITY_KEY);
37                 String  content_result = api.getTransResult(content.substring(3), "auto", "en");
38                 //2.处理翻译的结果
39                 //如:{"from":"zh","to":"en","trans_result":[{"src":"u4e2du56fd","dst":"Chinese"}]}
40                 char [] content_result_temp = content_result.toCharArray();
41                 content_result = "";//清空数据
42                 for(int i = content_result_temp.length-5;;i--) {
43                     if(content_result_temp[i] == '"') {
44                         break;
45                     }
46                     content_result = content_result_temp[i] + content_result;
47                 }
48                 //3.再写入
49                 com.po.TextMessage text = new com.po.TextMessage();
50                 text.setFromUserName(toUserName);//注意,这里发送者与接收者调换了
51                 text.setToUserName(fromUserName);
52                 text.setMsgType("text");//文本类型
53                 text.setCreateTime("" + new Date().getTime());//当前时间
54                 text.setContent(content_result);//返回消息
55                 //将文本消息转换为xml
56                 message = MessageUtil.textMessageToXml(text);
57                 
58                 System.out.println(message);
59             }
60             //如果是前缀是计算,则返回使用者的计算结果
61             if(content.startsWith("计算:")) {
62                 //1.先计算
63                 ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
64                 String  content_result = content.substring(3);
65                 content_result = "" + jse.eval(content_result);
66                 //2.再写入
67                 com.po.TextMessage text = new com.po.TextMessage();
68                 text.setFromUserName(toUserName);//注意,这里发送者与接收者调换了
69                 text.setToUserName(fromUserName);
70                 text.setMsgType("text");//文本类型
71                 text.setCreateTime("" + new Date().getTime());//当前时间
72                 text.setContent(content.substring(3) + "=" + content_result);//返回消息。注:从第一个分号开始截取
73                 //将文本消息转换为xml
74                 message = MessageUtil.textMessageToXml(text);
75                 
76                 System.out.println(message);
77             }
78         }
79         
80         out.print(message);//返回消息
81     } catch (DocumentException | ScriptException e) {
82         e.printStackTrace();
83     } finally {
84         out.close();
85     }
86 }

3.2  实现结果

原文地址:https://www.cnblogs.com/qijunhui/p/8445354.html