


Java WeChat development of uploading and downloading multimedia files_php example
Jul 06, 2016 pm 01:32 PM回復(fù)圖片、音頻、視頻消息都是需要media_id的,這個(gè)是需要將多媒體文件上傳到微信服務(wù)器才有的。
將多媒體文件上傳到微信服務(wù)器,以及從微信服務(wù)器下載文件,可以參考:http://mp.weixin.qq.com/wiki/index.php?title=上傳下載多媒體文件
上傳下載多媒體文件的方法還是寫(xiě)到WeixinUtil.java中。
代碼如下:
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.company.project.model.menu.AccessToken; import com.company.project.model.menu.Menu; public class WeixinUtil { private static Logger log = Logger.getLogger(WeixinUtil.class); public final static String APPID = "wxb927d4280e6db674"; public final static String APP_SECRET = "21441e9f3226eee81e14380a768b6d1e"; // 獲取access_token的接口地址(GET) 限200(次/天) public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; // 創(chuàng)建菜單 public final static String create_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN"; // 存放:1.token,2:獲取token的時(shí)間,3.過(guò)期時(shí)間 public final static Map<String,Object> accessTokenMap = new HashMap<String,Object>(); /** * 發(fā)起https請(qǐng)求并獲取結(jié)果 * * @param requestUrl 請(qǐng)求地址 * @param requestMethod 請(qǐng)求方式(GET、POST) * @param outputStr 提交的數(shù)據(jù) * @return JSONObject(通過(guò)JSONObject.get(key)的方式獲取json對(duì)象的屬性值) */ public static JSONObject handleRequest(String requestUrl,String requestMethod,String outputStr) { JSONObject jsonObject = null; try { URL url = new URL(requestUrl); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); SSLContext ctx = SSLContext.getInstance("SSL", "SunJSSE"); TrustManager[] tm = {new MyX509TrustManager()}; ctx.init(null, tm, new SecureRandom()); SSLSocketFactory sf = ctx.getSocketFactory(); conn.setSSLSocketFactory(sf); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod(requestMethod); conn.setUseCaches(false); if ("GET".equalsIgnoreCase(requestMethod)) { conn.connect(); } if (StringUtils.isNotEmpty(outputStr)) { OutputStream out = conn.getOutputStream(); out.write(outputStr.getBytes("utf-8")); out.close(); } InputStream in = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in,"utf-8")); StringBuffer buffer = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { buffer.append(line); } in.close(); conn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); log.error("URL錯(cuò)誤!"); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return jsonObject; } /** * 獲取access_token * * @author qincd * @date Nov 6, 2014 9:56:43 AM */ public static AccessToken getAccessToken(String appid,String appSecret) { AccessToken at = new AccessToken(); // 每次獲取access_token時(shí),先從accessTokenMap獲取,如果過(guò)期了就重新從微信獲取 // 沒(méi)有過(guò)期直接返回 // 從微信獲取的token的有效期為2個(gè)小時(shí) if (!accessTokenMap.isEmpty()) { Date getTokenTime = (Date) accessTokenMap.get("getTokenTime"); Calendar c = Calendar.getInstance(); c.setTime(getTokenTime); c.add(Calendar.HOUR_OF_DAY, 2); getTokenTime = c.getTime(); if (getTokenTime.after(new Date())) { log.info("緩存中發(fā)現(xiàn)token未過(guò)期,直接從緩存中獲取access_token"); // token未過(guò)期,直接從緩存獲取返回 String token = (String) accessTokenMap.get("token"); Integer expire = (Integer) accessTokenMap.get("expire"); at.setToken(token); at.setExpiresIn(expire); return at; } } String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appSecret); JSONObject object = handleRequest(requestUrl, "GET", null); String access_token = object.getString("access_token"); int expires_in = object.getInt("expires_in"); log.info("\naccess_token:" + access_token); log.info("\nexpires_in:" + expires_in); at.setToken(access_token); at.setExpiresIn(expires_in); // 每次獲取access_token后,存入accessTokenMap // 下次獲取時(shí),如果沒(méi)有過(guò)期直接從accessTokenMap取。 accessTokenMap.put("getTokenTime", new Date()); accessTokenMap.put("token", access_token); accessTokenMap.put("expire", expires_in); return at; } /** * 創(chuàng)建菜單 * * @author qincd * @date Nov 6, 2014 9:56:36 AM */ public static boolean createMenu(Menu menu,String accessToken) { String requestUrl = create_menu_url.replace("ACCESS_TOKEN", accessToken); String menuJsonString = JSONObject.fromObject(menu).toString(); JSONObject jsonObject = handleRequest(requestUrl, "POST", menuJsonString); String errorCode = jsonObject.getString("errcode"); if (!"0".equals(errorCode)) { log.error(String.format("菜單創(chuàng)建失敗!errorCode:%d,errorMsg:%s",jsonObject.getInt("errcode"),jsonObject.getString("errmsg"))); return false; } log.info("菜單創(chuàng)建成功!"); return true; } // 上傳多媒體文件到微信服務(wù)器 public static final String upload_media_url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; /** * 上傳多媒體文件到微信服務(wù)器<br> * @see http://www.oschina.net/code/snippet_1029535_23824 * @see http://mp.weixin.qq.com/wiki/index.php?title=上傳下載多媒體文件 * * @author qincd * @date Nov 6, 2014 4:11:22 PM */ public static JSONObject uploadMediaToWX(String filePath,String type,String accessToken) throws IOException{ File file = new File(filePath); if (!file.exists()) { log.error("文件不存在!"); return null; } String url = upload_media_url.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type); URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); // 設(shè)置邊界 String BOUNDARY = "----------" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); // 請(qǐng)求正文信息 // 第一部分: 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(conn.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(); // 結(jié)尾部分 byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定義最后數(shù)據(jù)分隔線 out.write(foot); out.flush(); out.close(); /** * 讀取服務(wù)器響應(yīng),必須讀取,否則提交不成功 */ try { // 定義BufferedReader輸入流來(lái)讀取URL的響應(yīng) StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); conn.disconnect(); return JSONObject.fromObject(buffer.toString()); } catch (Exception e) { log.error("發(fā)送POST請(qǐng)求出現(xiàn)異常!" + e); e.printStackTrace(); } return null; } public static final String download_media_url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"; /** * 從微信服務(wù)器下載多媒體文件 * * @author qincd * @date Nov 6, 2014 4:32:12 PM */ public static String downloadMediaFromWx(String accessToken,String mediaId,String fileSavePath) throws IOException { if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(mediaId)) return null; String requestUrl = download_media_url.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId); URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); InputStream in = conn.getInputStream(); File dir = new File(fileSavePath); if (!dir.exists()) { dir.mkdirs(); } if (!fileSavePath.endsWith("/")) { fileSavePath += "/"; } String ContentDisposition = conn.getHeaderField("Content-disposition"); String weixinServerFileName = ContentDisposition.substring(ContentDisposition.indexOf("filename")+10, ContentDisposition.length() -1); fileSavePath += weixinServerFileName; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileSavePath)); byte[] data = new byte[1024]; int len = -1; while ((len = in.read(data)) != -1) { bos.write(data,0,len); } bos.close(); in.close(); conn.disconnect(); return fileSavePath; } }
測(cè)試代碼:
public class WeixinUtilTest { /** * * @author qincd * @date Nov 6, 2014 9:57:54 AM */ public static void main(String[] args) { // 1).獲取access_token AccessToken accessToken = WeixinUtil.getAccessToken(WeixinUtil.APPID, WeixinUtil.APP_SECRET); String filePath = "C:\\Users\\qince\\Pictures\\壁紙20141029091612.jpg"; JSONObject uploadJsonObj = testUploadMedia(filePath,"image",accessToken.getToken()); if (uploadJsonObj == null) { System.out.println("上傳圖片失敗"); return; } int errcode = 0; if (uploadJsonObj.containsKey("errcode")) { errcode = uploadJsonObj.getInt("errcode"); } if (errcode == 0) { System.out.println("圖片上傳成功"); String mediaId = uploadJsonObj.getString("media_id"); long createAt = uploadJsonObj.getLong("created_at"); System.out.println("--Details:"); System.out.println("media_id:" + mediaId); System.out.println("created_at:" + createAt); } else { System.out.println("圖片上傳失??!"); String errmsg = uploadJsonObj.getString("errmsg"); System.out.println("--Details:"); System.out.println("errcode:" + errcode); System.out.println("errmsg:" + errmsg); } String mediaId = "6W-UvSrQ2hkdSdVQJJXShwtFDPLfbGI1qnbNFy8weZyb9Jac2xxxcAUwt8p4sYPH"; String filepath = testDownloadMedia(accessToken.getToken(), mediaId, "d:/test"); System.out.println(filepath); } /** * 上傳多媒體文件到微信 * * @author qincd * @date Nov 6, 2014 4:15:14 PM */ public static JSONObject testUploadMedia(String filePath,String type,String accessToken) { try { return WeixinUtil.uploadMediaToWX(filePath, type, accessToken); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 從微信下載多媒體文件 * * @author qincd * @date Nov 6, 2014 4:56:25 PM */ public static String testDownloadMedia(String accessToken,String mediaId,String fileSaveDir) { try { return WeixinUtil.downloadMediaFromWx(accessToken, mediaId, fileSaveDir); } catch (IOException e) { e.printStackTrace(); } return null; } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Yes, but there are restrictions. ① You can log in to the same account on both iPhone and Android phones, but logging in to the latest device will cause the earliest session to be offline; ② You can log in at the same time on the mobile phone and the computer desktop, but the functions are not synchronized; ③ Although using third-party tools or dual-app functions can enable logging in between two mobile phones, it is unofficially supported and may violate regulations; ④ Alternative solutions include using web version/desktop version to match the main phone, or transferring chat records through cloud backup and file tools. Some Android machines can also use "dual applications" to run two account instances.

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.
