1、微信上传文件接口
public String uploadFile(String url,String filePath,String type) throws Exception {
File file = new File(filePath);
String result = null;
if (!file.exists() || !file.isFile()) {
return "文件路径错误";
}
/**
* 第一部分
*/
url = url+"&type="+type;
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
/**
* 设置关键值
*/
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY);
//con.setRequestProperty("Content-Type", "multipart/mixed; boundary=" + BOUNDARY);
//con.setRequestProperty("content-type", "text/html");
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
out.write(head);
// 文件正文部分
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
/**
* 读取服务器响应,必须读取,否则提交不成功
*/
// con.getResponseCode();
/**
* 下面的方式读取也是可以的
*/
try {
// 定义BufferedReader输入流来读取URL的响应
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream(),"UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
//System.out.println(line);
buffer.append(line);
}
if(result==null){
result = buffer.toString();
}
System.out.println(buffer.toString());
return buffer.toString();
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
return result;
}
2、获取临时素材mediaId接口
public String uploadFile(String access_token,String filePath,String type){
String sendGetUrl=PropertyUtils.getPropertyValue(new File(realPathResolver.get(Constants.JEECMS_CONFIG)),UPLOAD_KEY);
String url = sendGetUrl+"?access_token=" + access_token;
String result = null;
String mediaId="";
FileUpload fileUpload = new FileUpload();
try {
result = fileUpload.uploadFile(url,filePath, type);
JSONObject json=new JSONObject(result);
mediaId=json.getString("media_id");
} catch (Exception e) {
e.printStackTrace();
}
return mediaId;
}
3、上传图文消息获取mediaId接口
public String uploadNews(String access_token,List<String> titles, List<String> descriptions, List<String> urls
, List<String> mediaIds, List<String> txts) {
try {
String sendUrl=PropertyUtils.getPropertyValue(new File(realPathResolver.get(Constants.JEECMS_CONFIG)),UPLOADNEWS_KEY);
sendUrl = sendUrl+"?access_token=" + access_token;
String strJson = "{\"articles\":[";
for (int i = 0; i < mediaIds.size(); i++) {
strJson += "{\"thumb_media_id\":\"" + mediaIds.get(i) + "\"";
strJson += ",\"title\":\"" + titles.get(i) + "\"";
strJson += ",\"content_source_url\":\"" + urls.get(i) + "\"";
String txt = txts.get(i);
txt = txt.replace("\"", "\\\"");
System.out.println(txt);
strJson += ",\"content\":\""+txt+"\"";
strJson += ",\"digest\":\"" + descriptions.get(i) + "\"";
strJson += ",\"show_cover_pic\":0";
strJson += "}";
if (i != mediaIds.size()-1) {
strJson += ",";
}
}
strJson += "]}";
System.out.println(strJson);
JSONObject tokenJson = getPostResponse(sendUrl, strJson);
return (String) tokenJson.get("media_id");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
4、推送接口
public void sendMassContent(String access_token, String mediaId) {
String sendUrl=PropertyUtils.getPropertyValue(new File(realPathResolver.get(Constants.JEECMS_CONFIG)),MASS_SEND_KEY);
sendUrl = sendUrl+"?access_token=" + access_token;
String strJson = "{";
//发送给所有关注者消息
strJson += "\"filter\":{";
strJson += "\"is_to_all\":true" +
"},";
strJson += "\"mpnews\":{";
strJson += "\"media_id\":\""+mediaId+"\"";
strJson += "},";
strJson += "\"msgtype\":\"mpnews\"";
strJson += "}";
post(sendUrl, strJson);
}
5、post请求(应该解析返回的string,提示成功失败)
private void post(String url, String json)
{
DefaultHttpClient client = new DefaultHttpClient();
client = (DefaultHttpClient) wrapClient(client);
HttpPost post = new HttpPost(url);
try
{
StringEntity s = new StringEntity(json,"utf-8");
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = client.execute(post);
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
System.out.println(result);
log.info(result);
}
catch (Exception e)
{
e.printStackTrace();
}
}
正确如下:
public JSONObject getPostResponse(String url, String json) {
DefaultHttpClient client = new DefaultHttpClient();
client = (DefaultHttpClient) wrapClient(client);
HttpPost post = new HttpPost(url);
try {
StringEntity s = new StringEntity(json, "utf-8");
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = client.execute(post);
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
return new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
6、组装内容
public int sendMassMessage(List<Content> beans, List<ContentExt> ext, List<ContentTxt> txt, String path){
List<String> titles = new ArrayList<String>();
List<String> descriptions = new ArrayList<String>();
List<String> urls = new ArrayList<String>();
List<String> mediaIds = new ArrayList<String>();
List<String> txts = new ArrayList<String>();
String token=weixinTokenCache.getToken();
for (int i = 0; i < beans.size(); i++) {
Content bean = beans.get(i);
//CmsSite site=bean.getSite();
String title = ext.get(i).getTitle();
titles.add(title);
String description = ext.get(i).getDescription();
descriptions.add(description);
String url = bean.getUrl();
String contentTxt = bean.getTxt();
txts.add(contentTxt);
urls.add(url);
String mediaId = uploadFile(token, path + bean.getTypeImg(), "image");
if (StringUtils.isBlank(mediaId)) {
return 0;
}
mediaIds.add(mediaId);
}
String mediaId = uploadNews(token, titles, descriptions, urls, mediaIds, txts);
sendMassContent(token, mediaId);
return 1;
}
7、测试用的预览
public void preview(String access_token, String mediaId) {
String sendUrl = "
https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=" + access_token;
String strJson = "{";
//发送给所有关注者消息
strJson += "\"touser\":\"xxx\""
+ ",";
strJson += "\"mpnews\":{";
strJson += "\"media_id\":\""+mediaId+"\"";
strJson += "},";
strJson += "\"msgtype\":\"mpnews\"";
strJson += "}";
post(sendUrl, strJson);
}