MessageUtil.java
7.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package com.server.utils.weixin;
import com.alibaba.fastjson.JSON;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.utils.Charsets;
import com.jfinal.weixin.sdk.utils.IOUtils;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* 公众号发送图片等
* Created by dell on 2018/2/28.
*/
public class MessageUtil {
private static Logger logger = LoggerFactory.getLogger(MessageUtil.class);
private static String customMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
//素材上传地址
private static String MEDIA_UPLOADURL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=";
public MessageUtil() {
}
private static Map<String,Object> sendMsg(Map<String, Object> message,String accessToken) {
String jsonResult = HttpURLUtil.post(customMessageUrl + accessToken, JsonUtils.toJson(message));
Map resultMap = (Map) JSON.parseObject(jsonResult, Map.class);
// Number number = (Number)resultMap.get("errcode");
// Integer errorCode = (number == null?null:Integer.valueOf(number.intValue()));
// if(errorCode == null || errorCode.intValue() == 0){
// return resultMap;
// }else{
// logger.error("MessageUtil.sendMsg==="+jsonResult+";message="+ReturnCode.get(errorCode));
// return resultMap;
// }
return resultMap;
}
/**
* 发送文本消息
* @param openId
* @param text
* @param accessToken
* @return
*/
public static Map<String,Object> sendText(String openId, String text,String accessToken) {
HashMap json = new HashMap();
json.put("touser", openId);
json.put("msgtype", "text");
HashMap textObj = new HashMap();
textObj.put("content", text);
json.put("text", textObj);
return sendMsg(json,accessToken);
}
/**
* 发送图片消息
* @param openId
* @param media_id
* @param accessToken
* @return
*/
public static Map<String,Object> sendImage(String openId, String media_id,String accessToken) {
HashMap json = new HashMap();
json.put("touser", openId);
json.put("msgtype", "image");
HashMap image = new HashMap();
image.put("media_id", media_id);
json.put("image", image);
return sendMsg(json,accessToken);
}
/**
* 上传临时素材库
* @param accessToken
* @param fileUrl
* @return
*/
public static Map<String,Object> mediaUploadImageMedia(String accessToken,String fileUrl) {
Map<String,Object> resultMap = new HashMap<String,Object>();
String url = MEDIA_UPLOADURL + accessToken + "&type=image";
String jsonStr = null;
try {
jsonStr = uploadMedia(url, fileUrl, (String)null);
} catch (IOException e) {
e.printStackTrace();
}
ApiResult apiResult = new ApiResult(jsonStr);
resultMap.put("jsonStr",jsonStr);
if(apiResult.isSucceed()){
resultMap.put("mediaId",apiResult.get("media_id"));
}else{
resultMap.put("mediaId","");
}
return resultMap;
}
protected static String uploadMedia(String url, String fileUrl,String params) throws IOException {
URL urlGet = new URL(url);
HttpURLConnection conn = (HttpURLConnection)urlGet.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
conn.setRequestProperty("Charsert", "UTF-8");
String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL";
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
StringBuilder mediaData = new StringBuilder();
mediaData.append("--").append(BOUNDARY).append("\r\n");
mediaData.append("Content-Disposition: form-data;name=\"media\";filename=\"" + new File(fileUrl).getName()+ "\"\r\n");
mediaData.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] mediaDatas = mediaData.toString().getBytes();
out.write(mediaDatas);
out.write(downLoadFromUrl(fileUrl));
out.write("\r\n".getBytes());
if(StrKit.notBlank(params)) {
StringBuilder end_data = new StringBuilder();
end_data.append("--").append(BOUNDARY).append("\r\n");
end_data.append("Content-Disposition: form-data;name=\"description\";");
byte[] in = end_data.toString().getBytes();
out.write(in);
out.write(params.getBytes(Charsets.UTF_8));
}
byte[] end_data1 = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(end_data1);
out.flush();
IOUtils.closeQuietly(out);
InputStream in1 = conn.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in1, Charsets.UTF_8));
String valueString = null;
StringBuffer bufferRes = null;
bufferRes = new StringBuffer();
while((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
IOUtils.closeQuietly(in1);
if(conn != null) {
conn.disconnect();
}
return bufferRes.toString();
}
/**
* 从网络Url中下载文件
* @param urlStr
* @throws IOException
*/
public static byte[] downLoadFromUrl(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
// //文件保存位置
// File saveDir = new File(savePath);
// if(!saveDir.exists()){
// saveDir.mkdir();
// }
// File file = new File(saveDir+File.separator+fileName);
// FileOutputStream fos = new FileOutputStream(file);
// fos.write(getData);
// if(fos!=null){
// fos.close();
// }
// if(inputStream!=null){
// inputStream.close();
// }
return getData;
}
/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}