2019年3月11号, 以下内容都是2015年写的东西,可能已经不能用
weixin-java-tools,现已更名Wxjava,一直使用这个,很方便,建议大家使用,如果有空到时候写一篇关于Wxjava使用的文章
github地址:https://github.com/Wechat-Group/WxJava
以下内容为2015年所写
微信端发来信息格式:
<pre name="code" class="html"><xml>
<ToUserName><![CDATA[jj]]></ToUserName>
<FromUserName><![CDATA[pll]]></FromUserName>
<CreateTime>1439349572</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[]]></Content>
<MsgId>1234567890123456</MsgId>
</xml>
后台接收:
/**
* 解析微信发来的请求(XML)
*
* @param request
* @return
* @throws Exception
*/
public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
// 将解析结果存储在HashMap中
Map<String, String> map = new HashMap<String, String>();
// 从request中取得输入流
InputStream inputStream = request.getInputStream();
// 读取输入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到xml根元素
Element root = document.getRootElement();
// 得到根元素的所有子节点
List<Element> elementList = root.elements();
// 遍历所有子节点
for (Element e : elementList){
if(e.isTextOnly()){
map.put(e.getName(), e.getText());
}else{//处理扫码二维码,有二层结构
List<Element> scanInfo = e.elements();
for(Element i :scanInfo){
map.put(i.getName(), i.getText());
}
}
}
// 释放资源
inputStream.close();
inputStream = null;
return map;
}
public void doMessage ()throws Exception {
// 获取请求和响应
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
String result = "";
if(echostr != null && echostr.length() > 1) {
System.out.println("signature:"+signature);
System.out.println("timestamp:"+timestamp);
System.out.println("nonce:"+nonce);
System.out.println("echostr:"+echostr);
}else{
// xml请求解析
Map<String, String> requestMap = MessageUtil.parseXml(request);
LoggerUtil.weixinLog("收到来自微信的消息:"+requestMap.toString());
//正常的微信处理流程
// 发送方帐号(open_id)也是回复消息的接收者
String to = requestMap.get("FromUserName");
// 公众帐号 也是回复消息的发送者
String from = requestMap.get("ToUserName");
// 消息类型
String msgType = requestMap.get("MsgType");
if(msgType.equals("text")){
//用户发送的文本信息
String content = requestMap.get("Content").trim();
}else if(msgType.equals("image")){
String content = "你发送了一张图片";
result = FormatXmlProcess.textAnswer(to,from,content);
}else if(msgType.equals("link")){
String content = "你发送了一个链接地址";
result = FormatXmlProcess.textAnswer(to,from,content);
}else if(msgType.equals("voice")){
String content = "您发送了一个声音";
result = FormatXmlProcess.textAnswer(to,from,content);
}else if(msgType.equals("video")){
String content = "你发送了一个视频";
result = FormatXmlProcess.textAnswer(to,from,content);
}else if(msgType.equals("location")){
String location_x = requestMap.get("Location_X");
String location_y = requestMap.get("Location_Y");
String label = requestMap.get("Label");
String content = "您的当前位置:X("+location_x+"),Y("+location_y+")"+label;
result = FormatXmlProcess.textAnswer(to,from,content);
}else{
String content = "暂时无相应服务。。。";
result = FormatXmlProcess.textAnswer(to,from,content);
}
}
}
/**
* 从微信下载语音,并存储到硬盘
* @Title: handleVoice
* @Description: TODO(从微信下载语音,并存储到硬盘)
* @author pll
* @param @param userid 用户ID
* @param @param mediaId 从微信下载所需语音ID
* @return void 返回类型
* @throws
*/
public static void handleVoice(Long userid,String mediaId){
//accesstoken
String accesstoken="accesstoken";
InputStream is = null;
String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+ accesstoken + "&media_id=" + mediaId;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
// 获取文件转化为byte流
is = http.getInputStream();
//存储到硬盘,原本音频格式为amr
String sourcePath=FileTool.writeFile(is, "_"+userid+".amr","voice");
//arm Convert Mp3
changeToMp3(sourcePath+"_"+userid+".amr",sourcePath+"_"+userid+".mp3");
} catch (Exception e) {
e.printStackTrace();
}
}
此处需要一个jar包 java-1.0.2.jar
/**
* 把amr格式的语音转换成MP3
* @Title: changeToMp3
* @Description: TODO(把amr格式的语音转换成MP3)
* @author pll
* @param @param sourcePath amr格式文件路径
* @param @param targetPath 存放mp3格式文件路径
* @return void 返回类型
* @throws
*/
public static void changeToMp3(String sourcePath, String targetPath) {
File source = new File(sourcePath);
File target = new File(targetPath);
AudioAttributes audio = new AudioAttributes();
Encoder encoder = new Encoder();
audio.setCodec("libmp3lame");
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp3");
attrs.setAudioAttributes(audio);
try {
encoder.encode(source, target, attrs);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InputFormatException e) {
e.printStackTrace();
} catch (EncoderException e) {
e.printStackTrace();
}
}