微信的图片上传和下载
最近在研究微信的图片上传和下载,查看了很多资料,和自己的摸索,将其总结一下。
一。上传
二。下载
package com.cxb.wx.media;
/**
* 微信通用接口凭证
*
* @author Engineer-Jsp
* @date 2014.06.23
*/
public class AccessToken {
// 获取到的凭证
private String token;
// 凭证有效时间,单位:秒
private int expiresIn;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}
package com.cxb.wx.media;
/**
* @author ChenXb
*
* 2018年4月27日
*/
public class WeixinMedia {
//媒体文件类型
private String type;
//媒体文件标识或缩略图的媒体文件标识
private String mediaId;
//媒体文件上传的时间
private int createdAt;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public int getCreatedAt() {
return createdAt;
}
public void setCreatedAt(int createdAt) {
this.createdAt = createdAt;
}
@Override
public String toString() {
return "WxMedia [type=" + type + ", mediaId=" + mediaId + ", createdAt=" + createdAt + "]";
}
}
package com.cxb.wx.media;
/**
* @author Engineer-Jsp
* @date 2014.10.09
* 请求数据通用类*/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.cxb.wx.menu.Menu;
import net.sf.json.JSONObject;
public class WeixinUtil {
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject HttpRequest(String request , String RequestMethod , String output ){
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
//建立连接
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(RequestMethod);
if(output!=null){
OutputStream out = connection.getOutputStream();
out.write(output.getBytes("UTF-8"));
out.close();
}
//流处理
InputStream input = connection.getInputStream();
InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
BufferedReader reader = new BufferedReader(inputReader);
String line;
while((line=reader.readLine())!=null){
buffer.append(line);
}
//关闭连接、释放资源
reader.close();
inputReader.close();
input.close();
input = null;
connection.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (Exception e) {
}
return jsonObject;
}
// 获取access_token的接口地址(GET)
public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* 获取access_token
*
* @param CorpID 企业Id
* @param SECRET 管理组的凭证**,每个secret代表了对应用、通讯录、接口的不同权限;不同的管理组拥有不同的secret
* @return
*/
public static AccessToken getAccessToken(String corpID, String secret) {
AccessToken accessToken = null;
String requestUrl = access_token_url.replace("APPID", corpID).replace("APPSECRET", secret);
JSONObject jsonObject = HttpRequest(requestUrl, "GET", null);
// 如果请求成功
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setToken(jsonObject.getString("access_token"));
accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
System.out.println("获取token成功:"+jsonObject.getString("access_token")+"————"+jsonObject.getInt("expires_in"));
} catch (Exception e) {
accessToken = null;
// 获取token失败
String error = String.format("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
System.out.println(error);
}
}
return accessToken;
}
// 菜单创建(POST)
public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
/**
* 创建菜单
*
* @param menu 菜单实例
* @param accessToken 有效的access_token
* @param agentid 企业应用的id,整型,可在应用的设置页面查看
* @return 0表示成功,其他值表示失败
*/
public static int createMenu(Menu menu, String accessToken) {
int result = 0;
// 拼装创建菜单的url
String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
// 将菜单对象转换成json字符串
String jsonMenu = JSONObject.fromObject(menu).toString();
// 调用接口创建菜单
JSONObject jsonObject = HttpRequest(url, "POST", jsonMenu);
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
result = jsonObject.getInt("errcode");
String error = String.format("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
System.out.println(error);
}
}
return result;
}
public static String URLEncoder(String str){
String result = str ;
try {
result = java.net.URLEncoder.encode(result,"UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 根据内容类型判断文件扩展名
*
* @param contentType 内容类型
* @return
*/
public static String getFileEndWitsh(String contentType) {
String fileEndWitsh = "";
if ("image/jpeg".equals(contentType))
fileEndWitsh = ".jpg";
else if ("audio/mpeg".equals(contentType))
fileEndWitsh = ".mp3";
else if ("audio/amr".equals(contentType))
fileEndWitsh = ".amr";
else if ("video/mp4".equals(contentType))
fileEndWitsh = ".mp4";
else if ("video/mpeg4".equals(contentType))
fileEndWitsh = ".mp4";
return fileEndWitsh;
}
/**
* 数据提交与请求通用方法
* @param access_token 凭证
* @param RequestMt 请求方式
* @param RequestURL 请求地址
* @param outstr 提交json数据
* */
public static int PostMessage(String access_token ,String RequestMt , String RequestURL , String outstr){
int result = 0;
RequestURL = RequestURL.replace("ACCESS_TOKEN", access_token);
JSONObject jsonobject = WeixinUtil.HttpRequest(RequestURL, RequestMt, outstr);
if (null != jsonobject) {
if (0 != jsonobject.getInt("errcode")) {
result = jsonobject.getInt("errcode");
String error = String.format("操作失败 errcode:{} errmsg:{}", jsonobject.getInt("errcode"), jsonobject.getString("errmsg"));
System.out.println(error);
}
}
return result;
}
}
package com.cxb.wx.media;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.cxb.wx.accesstoken.AccessTokenUtil;
import com.cxb.wx.accesstoken.Account;
import net.sf.json.JSONObject;
/**
* @author ChenXb
*
* 2018年4月27日
*/
public class MUDload {
/**
* 上传媒体文件
* @param accessToken 接口访问凭证
* @param type 媒体文件类型,分别有图片(image)、语音(voice)、视频(video),普通文件(file)
* @param media form-data中媒体文件标识,有filename、filelength、content-type等信息
* @param mediaFileUrl 媒体文件的url
* 上传的媒体文件限制
* 图片(image):1MB,支持JPG格式
* 语音(voice):2MB,播放长度不超过60s,支持AMR格式
* 视频(video):10MB,支持MP4格式
* 普通文件(file):10MB
* */
public static WeixinMedia uploadMedia(String accessToken, String type, String mediaFileUrl) {
WeixinMedia weixinMedia = null;
// 拼装请求地址
String uploadMediaUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
// 定义数据分隔符
String boundary = "------------7da2e536604c8";
try {
URL uploadUrl = new URL(uploadMediaUrl);
HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 设置请求头Content-Type
uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 获取媒体文件上传的输出流(往微信服务器写数据)
OutputStream outputStream = uploadConn.getOutputStream();
URL mediaUrl = new URL(mediaFileUrl);
HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
meidaConn.setDoOutput(true);
meidaConn.setRequestMethod("GET");
// 从请求头中获取内容类型
String contentType = meidaConn.getHeaderField("Content-Type");
// 根据内容类型判断文件扩展名
String fileExt = WeixinUtil.getFileEndWitsh(contentType);
// 请求体开始
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());
// 获取媒体文件的输入流(读取文件)
BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
// 将媒体文件写到输出流(往微信服务器写数据)
outputStream.write(buf, 0, size);
}
// 请求体结束
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
outputStream.close();
bis.close();
meidaConn.disconnect();
// 获取媒体文件上传的输入流(从微信服务器读数据)
InputStream inputStream = uploadConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
uploadConn.disconnect();
// 使用JSON-lib解析返回结果
JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
weixinMedia = new WeixinMedia();
weixinMedia.setType(jsonObject.getString("type"));
// type等于 缩略图(thumb) 时的返回结果和其它类型不一样
if ("thumb".equals(type))
weixinMedia.setMediaId(jsonObject.getString("thumb_media_id"));
else{
weixinMedia.setMediaId(jsonObject.getString("media_id"));
weixinMedia.setCreatedAt(jsonObject.getInt("created_at"));
}
} catch (Exception e) {
weixinMedia = null;
String error = String.format("上传媒体文件失败:%s", e);
System.out.println(error);
}
return weixinMedia;
}
/**
* 获取媒体文件
* @param accessToken 接口访问凭证
* @param media_id 媒体文件id
* @param savePath 文件在服务器上的存储路径
* */
public static String downloadMedia(String accessToken, String mediaId, String savePath) {
String filePath = null;
// 拼接请求地址
String requestUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
System.out.println(requestUrl);
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
if (!savePath.endsWith("/")) {
savePath += "/";
}
// 根据内容类型获取扩展名
String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));
// 将mediaId作为文件名
filePath = savePath + mediaId + fileExt;
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(new File(filePath));
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1){
fos.write(buf, 0, size);
}
fos.close();
bis.close();
conn.disconnect();
String info = String.format("下载媒体文件成功,filePath=" + filePath);
System.out.println(info);
} catch (Exception e) {
filePath = null;
String error = String.format("下载媒体文件失败:%s", e);
System.out.println(error);
}
return filePath;
}
/**
* 演示实例
*/
public static void main(String[] args) {
//这里获取accessToken 可以参考我的获取accessToken 博客完成。
//上传 这里模拟的是将图片放在Tomcat里面 http://localhost:8080/a.jpg 这里是Tomcat能访问的图片即可
WeixinMedia wxMedia = uploadMedia(accessToken, "image", "http://localhost:8080/a.jpg");
System.out.println(wxMedia.toString());
//下载
String mediaId = wxMedia.getMediaId();
String file = downloadMedia(accessToken, mediaId, "F:/****");
System.out.println(file);
}
}
执行效果:
需要的jar