public String uploadMaterial(String url,InputStream sbs,String filelength,String filename, String type) throws Exception {try {
DataInputStream in=new DataInputStream(sbs);url = url.replace("TYPE", type);URL urlObj = new URL(url);
// 創建Http連接HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();conn.setRequestMethod("POST");conn.setDoInput(true);conn.setDoOutput(true);conn.setUseCaches(false); // 使用post提交需要設置忽略緩存
// 消息請求頭信息conn.setRequestProperty("Connection", "Keep-Alive");conn.setRequestProperty("Charset", "UTF-8");
// 設置邊界String BOUNDARY = "----------" + System.currentTimeMillis();conn.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=\"media\";filename=\"" + filename + "\";filelength=\"" + filelength + "\"\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 ByteArrayInputStream(byts.getBytes(CharEncoding.UTF_8)));//in=new DataInputStream(meidaConn.getInputStream());int bytes = 0;byte[] bufferOut = new byte[1024 * 1024 * 10]; // 10Mwhile ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}
/*對類型為video的素材進行特殊處理*/if ("video".equals(type)) {out.write(("--" + BOUNDARY + "\r\n").getBytes());out.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());out.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}", filename, "miaoshu").getBytes());}
in.close();
// 結尾byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");out.write(foot);out.flush();out.close();
// 獲取響應StringBuffer buffer = new StringBuffer();BufferedReader reader = null;String result = null;try {reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line = null;while ((line = reader.readLine()) != null) {buffer.append(line);}if (result == null) {result = buffer.toString();}} catch (IOException e) {e.printStackTrace();} finally {reader.close();}
logger.info("uploadMaterial-result:" + result);return result;} catch (Exception e) {logger.error("uploadMaterial-ex:" + e.getMessage());throw e;}
}
public enum WxMaterialType {
WX_MATERIALTYPE_NEWS("news"), // 圖文WX_MATERIALTYPE_IMAGE("image"), // ??WX_MATERIALTYPE_VOICE("voice"), // 語音WX_MATERIALTYPE_VIDEO("video"),// 視頻WX_MATERIALTYPE_IMG("txtimg");//圖文中的圖片,僅在上傳圖文消息內的圖片獲取URL時使用
private String type;
WxMaterialType(String type) {this.type = type;}
public String getType() {return type;}
public void setType(String type) {this.type = type;}}
來源:博客園
作者:chuntao
鏈接:https://www.cnblogs.com/chuntao/p/11433324.html