微信公眾平臺(tái)開(kāi)發(fā)中使用Java挺好實(shí)現(xiàn)一個(gè)多媒體消息回復(fù)功能

微信公眾平臺(tái)開(kāi)發(fā)中使用Java挺好實(shí)現(xiàn)一個(gè)多媒體消息回復(fù)功能?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

創(chuàng)新互聯(lián)企業(yè)建站,10年網(wǎng)站建設(shè)經(jīng)驗(yàn),專注于網(wǎng)站建設(shè)技術(shù),精于網(wǎng)頁(yè)設(shè)計(jì),有多年建站和網(wǎng)站代運(yùn)營(yíng)經(jīng)驗(yàn),設(shè)計(jì)師為客戶打造網(wǎng)絡(luò)企業(yè)風(fēng)格,提供周到的建站售前咨詢和貼心的售后服務(wù)。對(duì)于成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)中不同領(lǐng)域進(jìn)行深入了解和探索,創(chuàng)新互聯(lián)在網(wǎng)站建設(shè)中充分了解客戶行業(yè)的需求,以靈動(dòng)的思維在網(wǎng)頁(yè)中充分展現(xiàn),通過(guò)對(duì)客戶行業(yè)精準(zhǔn)市場(chǎng)調(diào)研,為客戶提供的解決方案。

(一)素材接口圖片上傳

按照之前我們的約定將接口請(qǐng)求的url寫(xiě)入到配置文件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=

然后我在這里寫(xiě)了一個(gè)模擬表單上傳的工具類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頭和上傳文件內(nèi)容的分隔符 
    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(); 
  
      // 讀取返回?cái)?shù)據(jù) 
      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("發(fā)送POST請(qǐng)求出錯(cuò)。" + urlStr); 
      e.printStackTrace(); 
    } finally { 
      if (conn != null) { 
        conn.disconnect(); 
        conn = null; 
      } 
    } 
    return res; 
  } 
  
}

我們將工具類寫(xiě)好之后就需要在我們消息回復(fù)中加入對(duì)應(yīng)的響應(yīng)代碼,這里為了測(cè)試我將響應(yīng)代碼加在【關(guān)注事件】中!

(二)圖片回復(fù)

這里我們需要修改的是我們的【事件消息業(yè)務(wù)分發(fā)器】的代碼,這里我們將我們的回復(fù)加在【關(guān)注事件】中,簡(jiǎn)單代碼如下:

String openid = map.get("FromUserName"); // 用戶openid
String mpid = map.get("ToUserName"); // 公眾號(hào)原始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)) { // 關(guān)注事件
  System.out.println("==============這是關(guān)注事件!");
  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);
}

到這里代碼基本就已經(jīng)完成整個(gè)的圖片消息回復(fù)的內(nèi)容,同樣的不論是語(yǔ)音回復(fù)、視頻回復(fù)等流程都是一樣的,所以其他的就不在做過(guò)多的講述了,最后的大致效果如下:

微信公眾平臺(tái)開(kāi)發(fā)中使用Java挺好實(shí)現(xiàn)一個(gè)多媒體消息回復(fù)功能

看完上述內(nèi)容,你們掌握微信公眾平臺(tái)開(kāi)發(fā)中使用Java挺好實(shí)現(xiàn)一個(gè)多媒體消息回復(fù)功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

分享文章:微信公眾平臺(tái)開(kāi)發(fā)中使用Java挺好實(shí)現(xiàn)一個(gè)多媒體消息回復(fù)功能
分享鏈接:http://muchs.cn/article20/ihghco.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計(jì)、小程序開(kāi)發(fā)、營(yíng)銷型網(wǎng)站建設(shè)移動(dòng)網(wǎng)站建設(shè)、關(guān)鍵詞優(yōu)化、用戶體驗(yàn)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)