结合几位大佬的代码后实现此功能:感谢大佬让我完成此功能的实现,如有侵权,立刻删除。
借鉴文章地址:
java调用企业微信接口发送消息https://blog.csdn.net/zxl782340680/article/details/79876502。介绍的十分详细,相当感动,图片加代码。(这个是发送普通文本消息的)一下子代码就通过了。
corpID之类的页面参数告诉在哪里获取,支持下作者。
微信小程序客服消息新增临时素材接口java实现https://www.cnblogs.com/wbxk/p/8581195.html
代码
一、实体类:
注意:json字符串和实体类是对应的:一定要对应,我就是没有对应导致浪费一天半时间在修改40007错误。最后发现我输出出来的json和官方文档的不一样。这个是我踩的最大的坑media_id明明获取到了,确报40007media_id不合法,让我一直以为是我id获取错了,换了接口等,怎么都不好使。最后发现官方文档请求数据是这样的
我的是:
“media_id”:“获取到的media_id”没有前面的file。
相差这么大我竟然没发现,最后还是我公司哥给我发现的。希望自己以后认真一点吧。
/** * 微信消息发送实体类 * @author */ public class WeChatData { //发送微信消息的URLString sendMsgUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; /** * 成员账号 */ private String touser; /** * 消息类型 */ private String msgtype; /** * 企业应用的agentID */ private int agentid; /** * 实际接收Map类型数据 */ private Object file; public String getMsgtype() { return msgtype; } public void setMsgtype(String msgtype) { this.msgtype = msgtype; } public int getAgentid() { return agentid; } public void setAgentid(int agentid) { this.agentid = agentid; } public String getTouser() { return touser; } public void setTouser(String touser) { this.touser = touser; } public Object getFile() { return file; } public void setFile(Object file) { this.file = file; } }
二、微信授权请求
public class WeChatUrlData { /** * 企业Id */ private String corpid; /** * secret管理组的凭证密钥 */ private String corpsecret; /** * 获取ToKen的请求 */ private String Get_Token_Url; /** * 发送消息的请求 */ private String SendMessage_Url; public String getCorpid() { return corpid; } public void setCorpid(String corpid) { this.corpid = corpid; } public String getCorpsecret() { return corpsecret; } public void setCorpsecret(String corpsecret) { this.corpsecret = corpsecret; } public void setGet_Token_Url(String corpid,String corpsecret) { this.Get_Token_Url ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret; } public String getGet_Token_Url() { return Get_Token_Url; } public String getSendMessage_Url(){ SendMessage_Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; return SendMessage_Url; } }
三、微信发送消息
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.LoggerFactory; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; public class WeChatMsgSend { private CloseableHttpClient httpClient; /** * 用于提交登陆数据 */ private HttpPost httpPost; /** * 用于获得登录后的页面 */ private HttpGet httpGet; public static final String CONTENT_TYPE = "Content-Type"; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static Gson gson = new Gson(); /** * 微信授权请求,GET类型,获取授权响应,用于其他方法截取token * @param Get_Token_Url * @return String 授权响应内容 * @throws IOException */ protected String toAuth(String Get_Token_Url) throws IOException { httpClient = HttpClients.createDefault(); httpGet = new HttpGet(Get_Token_Url); CloseableHttpResponse response = httpClient.execute(httpGet); String resp; try { HttpEntity entity = response.getEntity(); resp = EntityUtils.toString(entity, "utf-8"); EntityUtils.consume(entity); } finally { response.close(); } LoggerFactory.getLogger(getClass()).info(" resp:{}", resp); return resp; } /**corpid应用组织编号 corpsecret应用秘钥 * 获取toAuth(String Get_Token_Url)返回结果中键值对中access_token键的值 * @param */ public String getToken(String corpid,String corpsecret) throws IOException { WeChatMsgSend sw = new WeChatMsgSend(); WeChatUrlData uData = new WeChatUrlData(); uData.setGet_Token_Url(corpid,corpsecret); String resp = sw.toAuth(uData.getGet_Token_Url()); System.out.println("resp=====:"+resp); try{ Map<String, Object> map = gson.fromJson(resp,new TypeToken<Map<String, Object>>() {}.getType()); return map.get("access_token").toString(); }catch (Exception e) { return resp; } } /** * @Title:创建微信发送请求post数据 * touser发送消息接收者 ,msgtype消息类型(文本/图片等), * application_id应用编号。 * media_id文件id,可以调用上传临时素材接口获取 * 本方法适用于text型微信消息,contentKey和contentValue只能组一对 * @return String */ public String createpostdata(String touser, String msgtype, int application_id,String file,Object media_id) { WeChatData wcd = new WeChatData(); wcd.setTouser(touser); wcd.setAgentid(application_id); wcd.setMsgtype(msgtype); Map<Object, Object> content = new HashMap<Object, Object>(); content.put(file,media_id); wcd.setFile(content); return gson.toJson(wcd); } /** * @Title 创建微信发送请求post实体 * charset消息编码 ,contentType消息体内容类型, * url微信消息发送请求地址,data为post数据,token鉴权token * @return String */ public String post(String charset, String contentType, String url, String data,String token) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); httpPost = new HttpPost(url+token); httpPost.setHeader(CONTENT_TYPE, contentType); httpPost.setEntity(new StringEntity(data, charset)); CloseableHttpResponse response = httpclient.execute(httpPost); String resp; try { HttpEntity entity = response.getEntity(); resp = EntityUtils.toString(entity, charset); EntityUtils.consume(entity); } finally { response.close(); } LoggerFactory.getLogger(getClass()).info("call [{}], param:{}, resp:{}", url, data, resp); return resp; } }
四、上传临时文件获取media_id
public class UploadMeida { /** * 新增临时素材 * * @param fileType * @param filePath * @return * @throws Exception */ public JSONObject UploadMeida(String fileType, String filePath) throws Exception { // 返回结果 String result = null; File file = new File(filePath); if (!file.exists() || !file.isFile()) { throw new IOException("文件不存在"); } WeChatMsgSend swx = new WeChatMsgSend(); String token = swx.getToken("ww6f36fa1463b963b0", "1PF1i9ypGkMakBd-8nKw9kUeZkc95opSkm8MJGChSMw"); if (token == null) { throw new IOException("未获取到token"); } String uploadTempMaterial_url="https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; uploadTempMaterial_url = uploadTempMaterial_url.replace("ACCESS_TOKEN", token).replace("TYPE", fileType); URL url = new URL(uploadTempMaterial_url); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST");// 以POST方式提交表单 conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false);// POST方式不能使用缓存 // 设置请求头信息 conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); // 设置边界 String BOUNDARY = "----------" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); // 请求正文信息 // 第一部分 StringBuilder sb = new StringBuilder(); sb.append("--");// 必须多两条道 sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\"; filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); // 获得输出流 OutputStream out = new DataOutputStream(conn.getOutputStream()); // 输出表头 out.write(sb.toString().getBytes("UTF-8")); // 文件正文部分 // 把文件以流的方式 推送道URL中 DataInputStream din = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] buffer = new byte[1024]; while ((bytes = din.read(buffer)) != -1) { out.write(buffer, 0, bytes); } din.close(); // 结尾部分 byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");// 定义数据最后分割线 out.write(foot); out.flush(); out.close(); if (HttpsURLConnection.HTTP_OK == conn.getResponseCode()) { StringBuffer strbuffer = null; BufferedReader reader = null; try { strbuffer = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String lineString = null; while ((lineString = reader.readLine()) != null) { strbuffer.append(lineString); } if (result == null) { result = strbuffer.toString(); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } } JSONObject jsonObject = JSONObject.parseObject(result); return jsonObject; } }
五、测试类
import com.alibaba.fastjson.JSONObject; import java.io.IOException; public class Test { public static void main(String[] args) { UploadMeida uploadMeida = new UploadMeida(); String fileType = "file"; String filePath = "src/main/resources/excel/工资条.xls"; WeChatMsgSend swx = new WeChatMsgSend(); try { String token = swx.getToken("你的corpID", "你的Secret"); JSONObject jsonObject = uploadMeida.UploadMeida(fileType, filePath); Object media_id = jsonObject.get("media_id"); String postdata = swx.createpostdata( "你要发送的账户名", "file", 1000002, "media_id", media_id); String resp = swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, token); System.out.println("获取到的toke n======>" + token); System.out.println("请求数据======>" + postdata); System.out.println("发送微信的响应数据======>" + resp); System.err.println(media_id); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }