Java tutorial
/** The MIT License (MIT) * Copyright (c) 2016 (mingsoft.net) * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mingsoft.weixin.util; 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.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import javax.servlet.http.HttpServletRequest; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.mingsoft.util.StringUtil; import com.mingsoft.weixin.http.HttpClientConnectionManager; /** * mswx-?</b> * Copyright: Copyright (c) 2014 - 2015 * Company:?? * @author wangtp * @version 300-001-001 * ? * Comments: ? * Create Date:2014-5-12 * Modification history: */ public class UploadDownUtils extends BaseUtils { /** * ?? */ public final static String UPLOAD_NEWS_MEDIA = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token="; /** */ public static final transient Logger log = Logger.getLogger(UploadDownUtils.class); /** * ?</br> * ?:??jpg?,128K</br> */ public static final String TYPE_IMAGE = "image"; /** * voice</br> * :256K?60s</br> * ?AMRMP3? </br> */ public static final String TYPE_VOICE = "voice"; /** * </br> * :1MB?MP4?</br> */ public static final String TYPE_VIDEO = "video"; /** * thumb???</br> * 64KB?JPG?</br> */ public static final String TYPE_THUMB = "thumb"; /** * @param appid ? * @param secret ?? */ public UploadDownUtils(String appid, String secret) { super(appid, secret); } /* * ? ??? image: 128K?JPG? * voice256K?60s?AMRMP3? video1MB?MP4? * thumb64KB?JPG? * ???3?3?media_id?????3media_id */ /** * ? ? * @param access_token ?? * @param msgType image?voice?videothumb * @param localFile * @return */ @Deprecated public static String uploadMedia(String access_token, String msgType, String localFile) { String media_id = null; String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type=" + msgType; String local_url = localFile; try { File file = new File(local_url); if (!file.exists() || !file.isFile()) { log.error("==" + local_url); return null; } URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); // Post????get? con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // post?? // ? con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); // String BOUNDARY = "----------" + System.currentTimeMillis(); con.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY); // con.setRequestProperty("Content-Type", // "multipart/mixed; boundary=" + BOUNDARY); // con.setRequestProperty("content-type", "text/html"); // ? // 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(con.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(); // byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// ?? out.write(foot); out.flush(); out.close(); /** * ????,????? */ // con.getResponseCode(); try { // BufferedReader???URL? StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { // System.out.println(line); buffer.append(line); } String respStr = buffer.toString(); log.debug("==respStr==" + respStr); try { JSONObject dataJson = JSONObject.parseObject(respStr); media_id = dataJson.getString("media_id"); } catch (Exception e) { log.error("==respStr==" + respStr, e); try { JSONObject dataJson = JSONObject.parseObject(respStr); return dataJson.getString("errcode"); } catch (Exception e1) { } } } catch (Exception e) { log.error("??POST?" + e); } } catch (Exception e) { log.error("?!=" + local_url); log.error("?!", e); } finally { } return media_id; } /** * ?? * @param newsUploadBeanList * @return json? {"type":"news","media_id":"CsEf3ldqkAYJAU6EJeIkStVDSvffUJ54vqbThMgplD-VJXXof6ctX5fI6-aYyUiQ","created_at":1391857799} * type:;media_id:/???;created_at: */ public String uploadNews(String newsUploadJson) { String accessToken = getAccessToken(); if (!StringUtil.isBlank(accessToken)) { HttpPost httpPost = HttpClientConnectionManager.getPostMethod(UPLOAD_NEWS_MEDIA + accessToken); try { httpPost.setEntity(new StringEntity(newsUploadJson, "UTF-8")); HttpResponse response = HTTPCLIENT.execute(httpPost); String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8"); logger.debug(jsonStr); JSONObject object = JSON.parseObject(jsonStr); return object.getString("media_id"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } /** * ? ? * @param access_token ?? * @param msgType image?voice?videothumb * @param localFile * @return ? */ public String uploadMedia(String msgType, String localFile, HttpServletRequest request) { String media_id = null; String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + getAccessToken() + "&type=" + msgType; String local_url = this.getRealPath(request, localFile); // String local_url = localFile; try { File file = new File(local_url); if (!file.exists() || !file.isFile()) { log.error("==" + local_url); return null; } URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); // Post????get? con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // post?? // ? con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); // String BOUNDARY = "----------" + System.currentTimeMillis(); con.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=\"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(con.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(); // byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// ?? out.write(foot); out.flush(); out.close(); /** * ????,????? */ // con.getResponseCode(); try { // BufferedReader???URL? StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { // System.out.println(line); buffer.append(line); } String respStr = buffer.toString(); log.debug("==respStr==" + respStr); try { JSONObject dataJson = JSONObject.parseObject(respStr); media_id = dataJson.getString("media_id"); } catch (Exception e) { log.error("==respStr==" + respStr, e); try { JSONObject dataJson = JSONObject.parseObject(respStr); return dataJson.getString("errcode"); } catch (Exception e1) { } } } catch (Exception e) { log.error("??POST?" + e); } } catch (Exception e) { log.error("?!=" + local_url); log.error("?!", e); } finally { } return media_id; } /** * ? * * @return */ @Deprecated public static String downMedia(String access_token, String msgType, String media_id, String path) { String localFile = null; // SimpleDateFormat df = new SimpleDateFormat("/yyyyMM/"); try { String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + media_id; // log.error(path); // ? ? URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); String xx = conn.getHeaderField("Content-disposition"); try { log.debug("===? +==?==" + xx); if (xx == null) { InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String line = null; String result = null; while ((line = reader.readLine()) != null) { if (result == null) { result = line; } else { result += line; } } System.out.println(result); JSONObject dataJson = JSONObject.parseObject(result); return dataJson.getString("errcode"); } } catch (Exception e) { } if (conn.getResponseCode() == 200) { String Content_disposition = conn.getHeaderField("Content-disposition"); InputStream inputStream = conn.getInputStream(); // // ? // Long fileSize = conn.getContentLengthLong(); // + String savePath = path + "/" + msgType; // ?? String fileName = StringUtil.getDateSimpleStr() + Content_disposition.substring(Content_disposition.lastIndexOf(".")).replace("\"", ""); // File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } // ?? if (!saveDirFile.canWrite()) { log.error("??"); throw new Exception(); } // System.out.println("------------------------------------------------"); // ? File file = new File(saveDirFile + "/" + fileName); FileOutputStream outStream = new FileOutputStream(file); int len = -1; byte[] b = new byte[1024]; while ((len = inputStream.read(b)) != -1) { outStream.write(b, 0, len); } outStream.flush(); outStream.close(); inputStream.close(); // ? localFile = fileName; } } catch (Exception e) { log.error("? !", e); } finally { } return localFile; } /** * ? * * @return */ public String downMedia(String msgType, String media_id, String path) { String localFile = null; // SimpleDateFormat df = new SimpleDateFormat("/yyyyMM/"); try { String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + getAccessToken() + "&media_id=" + media_id; // log.error(path); // ? ? URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); String xx = conn.getHeaderField("Content-disposition"); try { log.debug("===? +==?==" + xx); if (xx == null) { InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String line = null; String result = null; while ((line = reader.readLine()) != null) { if (result == null) { result = line; } else { result += line; } } System.out.println(result); JSONObject dataJson = JSONObject.parseObject(result); return dataJson.getString("errcode"); } } catch (Exception e) { } if (conn.getResponseCode() == 200) { String Content_disposition = conn.getHeaderField("Content-disposition"); InputStream inputStream = conn.getInputStream(); // // ? // Long fileSize = conn.getContentLengthLong(); // + String savePath = path + "/" + msgType; // ?? String fileName = StringUtil.getDateSimpleStr() + Content_disposition.substring(Content_disposition.lastIndexOf(".")).replace("\"", ""); // File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } // ?? if (!saveDirFile.canWrite()) { log.error("??"); throw new Exception(); } // System.out.println("------------------------------------------------"); // ? File file = new File(saveDirFile + "/" + fileName); FileOutputStream outStream = new FileOutputStream(file); int len = -1; byte[] b = new byte[1024]; while ((len = inputStream.read(b)) != -1) { outStream.write(b, 0, len); } outStream.flush(); outStream.close(); inputStream.close(); // ? localFile = fileName; } } catch (Exception e) { log.error("? !", e); } finally { } return localFile; } }