package com.yiju.util.weixin;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import com.yiju.util.Const;
import com.yiju.util.ConverterUtils;
import com.yiju.util.DesUtil;
import com.yiju.util.HttpUtils;
import com.yiju.util.JsonUtil;
import com.yiju.util.PageData;
import com.yiju.util.Tools;
public class WeixinUtil{
protected static Logger logger = Logger.getLogger(WeixinUtil.class);
/**
* @Title getAccesssToken
* @Description 根据appid 和secret 获取access_token
* @param appid
* @param secret
* @return
* @author Cynara-remix
* @Date 2016年10月11日 下午12:22:35
*/
public static String getAccessToken() {
try {
String token = ConverterUtils.toString(HttpUtils.httpGetRequest(Const.TOKEN_URL, new HashMap<String, Object>()));
System.out.println("token:"+token);
return DesUtil.dencodeJson(token);
}catch (Exception e) {
Logger.getLogger(WeixinUtil.class).error("本地获取token失败",e);
}
return "";
}
/**
* @Title sendMeetingMsg
* @Description 向微信端发送信息
* @param map
* @return
* @author Cynara-remix
* @Date 2016年10月11日 下午12:22:35
* https://api.weixin.qq.com/cgi-bin/message/mass/preview?
*/
public static Boolean sendMeetingMsg(String msgurl,Map<Object,Object> map){
String token =getAccessToken();
Boolean isSuccess = false;
if(Tools.isEmpty(token)){
return isSuccess;
}
try {
URL url = new URL(msgurl+"access_token="+token);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
OutputStream out = connection.getOutputStream();
out.write(JsonUtil.Object2gson(map).getBytes("UTF-8"));
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = in.readLine();
JSONObject jo = new JSONObject(line);
if("0".equals(ConverterUtils.toString(jo.get("errcode")))){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return isSuccess;
}
/**
* @desc :微信上传素材的请求方法
*
* @param requestUrl 微信上传临时素材的接口url
* @param file 要上传的文件
* @return String 上传成功后,微信服务器返回的消息
*/
public static net.sf.json.JSONObject uploadToWechat(String requestUrl, File file,String type) {
StringBuffer buffer = new StringBuffer();
String token =getAccessToken();
if(Tools.isEmpty(token)){
return null;
}
try{
//1.建立连接
URL url = new URL(requestUrl+"access_token="+token+"&type="+type);
logger.error("url-------------------------"+requestUrl+"access_token="+token+"&type="+type);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); //打开链接
//1.1输入输出设置
httpUrlConn.setDoInput(true);
httpUrlConn.setDoOutput(true);
httpUrlConn.setUseCaches(false); // post方式不能使用缓存
//1.2设置请求头信息
httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
//1.3设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
httpUrlConn.setRequestProperty("Content-Type","multipart/form-data; boundary="+ BOUNDARY);
// 请求正文信息
// 第一部分:
//2.将文件头输出到微信服务器
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
logger.error("file info ----------"+file.getName()+"-----filelength"+file.length());
sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
+ "\";filename=\""+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
// 将表头写入输出流中:输出表头
outputStream.write(head);
//3.将文件正文部分输出到微信服务器
// 把文件以流文件的方式 写入到微信服务器中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
outputStream.write(bufferOut, 0, bytes);
}
in.close();
//4.将结尾部分输出到微信服务器
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
outputStream.write(foot);
outputStream.flush();
outputStream.close();
//5.将微信服务器返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
str = buffer.toString();
logger.error("response content-------------------------"+str);
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
//4.json字符串转对象:解析返回值,json反序列化
str = str.replaceAll("[\\\\]", "");
logger.error("result:" + str);
net.sf.json.JSONObject resultJSON = net.sf.json.JSONObject.fromObject(str);
//5.返回参数判断
if (resultJSON != null) {
if (resultJSON.get("thumb_media_id") != null) {
System.out.println("上传" + type + "永久素材成功");
return resultJSON;
} else {
System.out.println("上传" + type + "永久素材失败");
}
}
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
return null;
}
return null;
}
public static String sendMpNews(Map<Object,Object> ar){
Map<String,List<Map<Object,Object>>> map = new HashMap<String,List<Map<Object,Object>>>();
List<Map<Object,Object>> list = new ArrayList<>();
list.add(ar);
map.put("articles", list);
String token =getAcce