微信公众平台开发中使用Java挺好实现一个多媒体消息回复功能

微信公众平台开发中使用Java挺好实现一个多媒体消息回复功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

(一)素材接口图片上传

按照之前我们的约定将接口请求的url写入到配置文件interface_url.properties中:

#获取token的url
tokenUrl=https://api.weixin.qq.com/cgi-bin/token
#永久多媒体文件上传url
mediaUrl=http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=

然后我在这里写了一个模拟表单上传的工具类HttpPostUploadUtil.java,如下:

package com.cuiyongzhi.wechat.util;
 
import java.io.BufferedReader; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.Iterator; 
import java.util.Map; 
 
import javax.activation.MimetypesFileTypeMap;
import com.cuiyongzhi.web.util.GlobalConstants;
 
/**
 * ClassName: HttpPostUploadUtil
 * @Description: 多媒体上传
 * @author dapengniao
 * @date 2016年3月14日 上午11:56:55
 */
public class HttpPostUploadUtil { 
   
  public String urlStr; 
   
  public HttpPostUploadUtil(){
    urlStr = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+GlobalConstants.getInterfaceUrl("access_token")+"&type=image"; 
  }
    
    
  
  /** 
   * 上传图片 
   * 
   * @param urlStr 
   * @param textMap 
   * @param fileMap 
   * @return 
   */ 
  @SuppressWarnings("rawtypes")
  public String formUpload(Map<String, String> textMap, 
      Map<String, String> fileMap) { 
    String res = ""; 
    HttpURLConnection conn = null; 
    String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符 
    try { 
      URL url = new URL(urlStr); 
      conn = (HttpURLConnection) url.openConnection(); 
      conn.setConnectTimeout(5000); 
      conn.setReadTimeout(30000); 
      conn.setDoOutput(true); 
      conn.setDoInput(true); 
      conn.setUseCaches(false); 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Connection", "Keep-Alive"); 
      conn 
          .setRequestProperty("User-Agent", 
              "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); 
      conn.setRequestProperty("Content-Type", 
          "multipart/form-data; boundary=" + BOUNDARY); 
  
      OutputStream out = new DataOutputStream(conn.getOutputStream()); 
      // text 
      if (textMap != null) { 
        StringBuffer strBuf = new StringBuffer(); 
        Iterator<&#63;> iter = textMap.entrySet().iterator(); 
        while (iter.hasNext()) { 
          Map.Entry entry = (Map.Entry) iter.next(); 
          String inputName = (String) entry.getKey(); 
          String inputValue = (String) entry.getValue(); 
          if (inputValue == null) { 
            continue; 
          } 
          strBuf.append("\r\n").append("--").append(BOUNDARY).append( 
              "\r\n"); 
          strBuf.append("Content-Disposition: form-data; name=\"" 
              + inputName + "\"\r\n\r\n"); 
          strBuf.append(inputValue); 
        } 
        out.write(strBuf.toString().getBytes()); 
      } 
  
      // file 
      if (fileMap != null) { 
        Iterator<&#63;> iter = fileMap.entrySet().iterator(); 
        while (iter.hasNext()) { 
          Map.Entry entry = (Map.Entry) iter.next(); 
          String inputName = (String) entry.getKey(); 
          String inputValue = (String) entry.getValue(); 
          if (inputValue == null) { 
            continue; 
          } 
          File file = new File(inputValue); 
          String filename = file.getName(); 
          String contentType = new MimetypesFileTypeMap() 
              .getContentType(file); 
          if (filename.endsWith(".jpg")) { 
            contentType = "image/jpg"; 
          } 
          if (contentType == null || contentType.equals("")) { 
            contentType = "application/octet-stream"; 
          } 
  
          StringBuffer strBuf = new StringBuffer(); 
          strBuf.append("\r\n").append("--").append(BOUNDARY).append( 
              "\r\n"); 
          strBuf.append("Content-Disposition: form-data; name=\"" 
              + inputName + "\"; filename=\"" + filename 
              + "\"\r\n"); 
          strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); 
  
          out.write(strBuf.toString().getBytes()); 
  
          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[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); 
      out.write(endData); 
      out.flush(); 
      out.close(); 
  
      // 读取返回数据 
      StringBuffer strBuf = new StringBuffer(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader( 
          conn.getInputStream())); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
        strBuf.append(line).append("\n"); 
      } 
      res = strBuf.toString(); 
      reader.close(); 
      reader = null; 
    } catch (Exception e) { 
      System.out.println("发送POST请求出错。" + urlStr); 
      e.printStackTrace(); 
    } finally { 
      if (conn != null) { 
        conn.disconnect(); 
        conn = null; 
      } 
    } 
    return res; 
  } 
  
}

我们将工具类写好之后就需要在我们消息回复中加入对应的响应代码,这里为了测试我将响应代码加在【关注事件】中!

(二)图片回复

这里我们需要修改的是我们的【事件消息业务分发器】的代码,这里我们将我们的回复加在【关注事件】中,简单代码如下:

String openid = map.get("FromUserName"); // 用户openid
String mpid = map.get("ToUserName"); // 公众号原始ID
ImageMessage imgmsg = new ImageMessage();
imgmsg.setToUserName(openid);
imgmsg.setFromUserName(mpid);
imgmsg.setCreateTime(new Date().getTime());
imgmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_Image);
if (map.get("Event").equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) { // 关注事件
  System.out.println("==============这是关注事件!");
  Image img = new Image();
  HttpPostUploadUtil util=new HttpPostUploadUtil();
  String filepath="H:\\1.jpg"; 
  Map<String, String> textMap = new HashMap<String, String>(); 
  textMap.put("name", "testname"); 
  Map<String, String> fileMap = new HashMap<String, String>(); 
  fileMap.put("userfile", filepath); 
  String mediaidrs = util.formUpload(textMap, fileMap);
  System.out.println(mediaidrs);
  String mediaid=JSONObject.fromObject(mediaidrs).getString("media_id");
  img.setMediaId(mediaid);
  imgmsg.setImage(img);
  return MessageUtil.imageMessageToXml(imgmsg);
}

到这里代码基本就已经完成整个的图片消息回复的内容,同样的不论是语音回复、视频回复等流程都是一样的,所以其他的就不在做过多的讲述了,最后的大致效果如下:

微信公众平台开发中使用Java挺好实现一个多媒体消息回复功能

看完上述内容,你们掌握微信公众平台开发中使用Java挺好实现一个多媒体消息回复功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!