微信小程序客服消息新增临时素材接口java实现

今天想在微信小程序的客服信息窗口里回复用户一个图片信息,发现还需要上传素材,但是微信文档的上传临时素材接口写的模模糊糊,无奈去百度,网上清一色的PHP实现方式,难道我穿越了?PHP已经把java给超越了?

微信接口文档地址:https://mp.weixin.qq.com/debug/wxadoc/dev/api/custommsg/material.html#新增临时素材

言归正传,终于还是找到了一篇博客的,java实现。现摘录如下,做了小部分修改:

 1     /**
 2      * 新增临时素材
 3      * 
 4      * @param fileType
 5      * @param filePath
 6      * @return
 7      * @throws Exception
 8      */
 9     public static JSONObject UploadMeida(String fileType, String filePath) throws Exception {
10         // 返回结果
11         String result = null;
12         File file = new File(filePath);
13         if (!file.exists() || !file.isFile()) {
14             logger.info("文件不存在");
15             throw new IOException("文件不存在");
16         }
17         String token = getToken();
18         if (token == null) {
19             logger.info("未获取到token");
20             throw new IOException("未获取到token");
21         }
22         String urlString = Constants.WX_APP_MEDIA_UPLOAD.replace("ACCESS_TOKEN", token).replace("TYPE", fileType);
23         URL url = new URL(urlString);
24         HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
25         conn.setRequestMethod("POST");// 以POST方式提交表单
26         conn.setDoInput(true);
27         conn.setDoOutput(true);
28         conn.setUseCaches(false);// POST方式不能使用缓存
29         // 设置请求头信息
30         conn.setRequestProperty("Connection", "Keep-Alive");
31         conn.setRequestProperty("Charset", "UTF-8");
32         // 设置边界
33         String BOUNDARY = "----------" + System.currentTimeMillis();
34         conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
35         // 请求正文信息
36         // 第一部分
37         StringBuilder sb = new StringBuilder();
38         sb.append("--");// 必须多两条道
39         sb.append(BOUNDARY);
40         sb.append("
");
41         sb.append("Content-Disposition: form-data;name="media"; filename="" + file.getName() + ""
");
42         sb.append("Content-Type:application/octet-stream

");
43         logger.debug("sb:" + sb);
44 
45         // 获得输出流
46         OutputStream out = new DataOutputStream(conn.getOutputStream());
47         // 输出表头
48         out.write(sb.toString().getBytes("UTF-8"));
49         // 文件正文部分
50         // 把文件以流的方式 推送道URL中
51         DataInputStream din = new DataInputStream(new FileInputStream(file));
52         int bytes = 0;
53         byte[] buffer = new byte[1024];
54         while ((bytes = din.read(buffer)) != -1) {
55             out.write(buffer, 0, bytes);
56         }
57         din.close();
58         // 结尾部分
59         byte[] foot = ("
--" + BOUNDARY + "--
").getBytes("UTF-8");// 定义数据最后分割线
60         out.write(foot);
61         out.flush();
62         out.close();
63         if (HttpsURLConnection.HTTP_OK == conn.getResponseCode()) {
64 
65             StringBuffer strbuffer = null;
66             BufferedReader reader = null;
67             try {
68                 strbuffer = new StringBuffer();
69                 reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
70                 String lineString = null;
71                 while ((lineString = reader.readLine()) != null) {
72                     strbuffer.append(lineString);
73 
74                 }
75                 if (result == null) {
76                     result = strbuffer.toString();
77                     logger.info("result:" + result);
78                 }
79             } catch (IOException e) {
80                 logger.error("发送POST请求出现异常!", e);
81                 e.printStackTrace();
82             } finally {
83                 if (reader != null) {
84                     reader.close();
85                 }
86             }
87 
88         }
89         JSONObject jsonObject = JSONObject.parseObject(result);
90         return jsonObject;
91 
92     }

使用的时候直接本地执行一个main方法就OK的

 1     /**
 2      * 上传素材,用于获取media_id
 3      * @param args
 4      */
 5     public static void main(String[] args) {
 6         
 7         String fileType = "image";
 8         String filePath = "E:/testupload/123456.jpg";
 9         try {
10             JSONObject jsonObject = UploadMeida(fileType, filePath);
11             System.err.println(jsonObject);
12         } catch (Exception e) {
13             e.printStackTrace();
14         }
15     }

其实后来这个临时素材不满足需求的,因为网上说的这种临时素材好像3天就会过期,反正微信文档是啥也没说,只说这是临时素材,囧!我想找个微信小程序的永久素材接口,然而并没有找到。只能改用图文链接回复了,把链接指向自己服务器上的一个图片。

原文地址:https://www.cnblogs.com/wbxk/p/8581195.html