微信公众号信息的推送使用的比较频繁, 找个地方备份下代码, 避免重复造轮子。
需要注意的是,基于会话而发送信息, 需要用户与该公众号进行交互,而且需要在交互之后的48小时内,才能做推送,每次会话,最多能够向用户发送20条信息,超过了就会发送失败,需要用户重新交互,才能继续发, 譬如,给该公众号发送信息,点击该公众号菜单。
以下是核心方法:
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_MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
/**
* 发送微信会话信息
* */
public static Map<String, String> sendSessionMessage(Map<String, String> map, String accessToken){
Map<String, String> reslutmap = new HashMap<String, String>();
try {
String url = WX_INFO_MEDIA_URL + accessToken;
JSONObject object = new JSONObject();
object.put("msgtype", "text");
JSONObject text = new JSONObject();
text.put("content", map.get("content"));
object.put("text", text);
String openid = map.get("openId");
object.put("touser", openid);
String result = httpPostWithJSON(url, object.toString()); //发送信息
JSONObject json = JSONObject.fromObject(result); //获取返回值
String status = json.getString("errcode");
System.out.println(result);
if ("0".equals(status)) {
reslutmap.put("status", "1");
reslutmap.put("reason", status);
return reslutmap;
} else {
log.info(">>>>>>>>>>media faild :" + openid);
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;
}
}
/**
* 发送基于微信会话发送图文信息
* */
public static Map<String, String> sendMediaByIdMessage(Map<String, String> map, String accessToken){
Map<String, String> reslutmap = new HashMap<String, String>();
try {
String url = WX_INFO_MEDIA_URL + accessToken;
JSONObject object = new JSONObject();
object.put("msgtype", "mpnews");
JSONObject text = new JSONObject();
text.put("media_id", map.get("mediaId"));
object.put("mpnews", text);
String openid = map.get("openId");
object.put("touser", openid);
String result = httpPostWithJSON(url, object.toString());
JSONObject json = JSONObject.fromObject(result);
String status = json.getString("errcode");
System.out.println(result);
if ("0".equals(status)) {
reslutmap.put("status", "1");
reslutmap.put("reason", status);
return reslutmap;
} else {
log.info(">>>>>>>>>>media faild :" + openid);
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)==========================