微信公众号做了好长时间, 最近没什么事情, 决定把以前的一些微信推送的一些核心方法共享出来。一般来说,微信文本的推送量一般都比较大,如果需要快速推送的时候,可以采用多线程进行调用,加快推送速度。
以下是微信推送的核心方法:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
public class SendMethodUtil {
private static Logger log = Logger.getLogger(SendMethodUtil.class);
private static final String WX_INFO_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
/**
* sendMessage(发送微信文本信息)
* @param map
* @return
*/
public static Map<String, String> sendTextMessage(Map<String, String> map, String accessToken) {
Map<String, String> reslutmap = new HashMap<String, String>();
try {
String url = WX_INFO_URL + accessToken;
com.alibaba.fastjson.JSONObject messageJson = new com.alibaba.fastjson.JSONObject();
com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
com.alibaba.fastjson.JSONObject datavc1 = new com.alibaba.fastjson.JSONObject();
com.alibaba.fastjson.JSONObject datavc2 = new com.alibaba.fastjson.JSONObject();
com.alibaba.fastjson.JSONObject datavc3 = new com.alibaba.fastjson.JSONObject();
com.alibaba.fastjson.JSONObject datavc4 = new com.alibaba.fastjson.JSONObject();
com.alibaba.fastjson.JSONObject datavc5 = new com.alibaba.fastjson.JSONObject();
com.alibaba.fastjson.JSONObject datavc6 = new com.alibaba.fastjson.JSONObject();
com.alibaba.fastjson.JSONObject datavc7 = new com.alibaba.fastjson.JSONObject();
messageJson.put("touser", map.get("openId"));
messageJson.put("template_id", map.get("templateId"));
messageJson.put("url", map.get("url"));
datavc1.put("value", map.get("firstvalue"));
datavc1.put("color", map.get("firstcolor"));
data.put("first", datavc1);
datavc2.put("value", map.get("keyword1value"));
datavc2.put("color", map.get("keyword1color"));
data.put("keyword1", datavc2);
datavc3.put("value", map.get("keyword2value"));
datavc3.put("color", map.get("keyword2color"));
data.put("keyword2", datavc3);
datavc4.put("value", map.get("keyword3value"));
datavc4.put("color", map.get("keyword3color"));
data.put("keyword3", datavc4);
datavc5.put("value", map.get("keyword4value"));
datavc5.put("color", map.get("keyword4color"));
data.put("keyword4", datavc5);
datavc6.put("value", map.get("keyword5value"));
datavc6.put("color", map.get("keyword5color"));
data.put("keyword5", datavc6);
datavc7.put("value", map.get("remark"));
datavc7.put("color", map.get("remarkcolor"));
data.put("remark", datavc7);
messageJson.put("data", data);
String message = messageJson.toJSONString(); //发送的消息转换成string
String result = httpPostWithJSON(url, message); //发送信息,并获取返回值
JSONObject json = JSONObject.fromObject(result); //
String status = json.getString("errcode"); //error 是0的时候代表成功,1代表失败;
//重新拼装符合自己也为需求的返回值
if ("0".equals(status)) {
reslutmap.put("status", "1");
reslutmap.put("reason", status);
return reslutmap;
} else {
log.info("sendFaile:" + result + " message:" + message);
reslutmap.put("status", "0");
reslutmap.put("reason", status);
return reslutmap;
}
} catch (Exception ex) {
ex.printStackTrace();
log.error(">>>send->" + ex);
reslutmap.put("status", "0");
reslutmap.put("reason", "system error");
return reslutmap;
}
}
/**
* httpPostWithJSON(这里用一句话描述这个方法的作用)
* @param url
* @param json
* @return
*/
public static String httpPostWithJSON(String url, String json) {
String ACCEPT_LANGUAGE = "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3";
String entityStr = null;
DefaultHttpClient httpClient = null;
try {
httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
StringEntity entity = new StringEntity(json, "UTF-8");
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded")); // "application/octet-stream"
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8"));
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.setHeader("Accept-Language", ACCEPT_LANGUAGE);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("Method failed:" + response.getStatusLine());
}
String content = getContent(response, "UTF-8");
return content;
} catch (IOException e) {
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(baos));
e.printStackTrace();
entityStr = baos.toString();
} catch (Exception ex) {
ex.printStackTrace();
log.error(">>>send->" + ex);
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e1) {
e1.printStackTrace();
log.error(">>>send->" + e1);
}
}
}
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
}
return entityStr;
}
/**
* getContent(这里用一句话描述这个方法的作用)
* @param response
* @param encode
* @return
* @throws IllegalStateException
* @throws IOException
*/
public static String getContent(HttpResponse response, String encode) throws IllegalStateException, IOException {
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
response.getEntity().writeTo(baos);
String bosStr = new String(baos.toByteArray(), "UTF-8");
return bosStr;
} catch (Exception ex) {
ex.printStackTrace();
log.error(">>>send->" + ex);
return null;
} finally {
if (baos != null) {
baos.close();
}
}
}
}
方法可以直接使用, 记录下, 以后在别的地方只可以直接应用, 不需要重复造轮子。如有错误, 请指正。
=======================关注公众号(zzqJava)==========================