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