微信服务器素材上传
调用示例(使用curl命令,用FORM表单方式上传一个图片):
curl -F [email protected] “https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN”
直接上代码-_-
/**
* 微信服务器素材上传
*
* @param file
* 表单名称media
* @param token
* access_token
* @param type
* type只支持四种类型素材(video/image/voice/thumb)
* @param upurl
* 使用微信提供的接口即可
*/
public static JSONObject uploadMedia(File file, String token, String type, String upurl) {
if (file == null || token == null || type == null) {
return null;
}
if (!file.exists()) {
logger.info("上传文件不存在,请检查!");
return null;
}
String url = upurl;
JSONObject jsonObject = null;
PostMethod post = new PostMethod(url);
post.setRequestHeader("Connection", "Keep-Alive");
post.setRequestHeader("Cache-Control", "no-cache");
FilePart media = null;
HttpClient httpClient = new HttpClient();
// 信任任何类型的证书
Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);
try {
media = new FilePart("media", file);
Part[] parts = new Part[] { new StringPart("access_token", token), new StringPart("type", type), media };
MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
post.setRequestEntity(entity);
int status = httpClient.executeMethod(post);
if (status == HttpStatus.SC_OK) {
String text = post.getResponseBodyAsString();
jsonObject = JSONObject.fromObject(text);
} else {
logger.info("upload Media failure status is:" + status);
}
} catch (FileNotFoundException execption) {
execption.printStackTrace();
} catch (HttpException execption) {
execption.printStackTrace();
} catch (IOException execption) {
execption.printStackTrace();
}
return jsonObject;
}
// 素材上传(POST)
规定上传地址
public static final String UPLOAD_MEDIA = “https://api.weixin.qq.com/cgi-bin/material/add_material”;
/**
* 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应
*
* @param url
* 请求地址 form表单url地址
* @param type
* 上传类型
* @param title
* 视频标题
* @param introduction
* 视频描述
* @return
*/
public static JSONObject uploadVideo(File file, String type, String title, String introduction, String token) {
String url = UPLOAD_MEDIA + "?access_token=" + token + "&type=" + type;
String result = null;
JSONObject jsonObject = null;
try {
URL uploadURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uploadURL.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
String boundary = "-----------------------------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream output = conn.getOutputStream();
output.write(("--" + boundary + "\r\n").getBytes());
output.write(
String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName())
.getBytes());
output.write("Content-Type: video/mp4 \r\n\r\n".getBytes());
byte[] data = new byte[1024];
int len = 0;
FileInputStream input = new FileInputStream(file);
while ((len = input.read(data)) > -1) {
output.write(data, 0, len);
}
/* 对类型为video的素材进行特殊处理 */
if ("video".equals(type)) {
output.write(("--" + boundary + "\r\n").getBytes());
output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
output.write(
String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}", title, introduction).getBytes());
}
output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
output.flush();
output.close();
input.close();
InputStream resp = conn.getInputStream();
StringBuffer sb = new StringBuffer();
while ((len = resp.read(data)) > -1)
sb.append(new String(data, 0, len, "utf-8"));
resp.close();
result = sb.toString();
jsonObject = JSONObject.fromObject(result);
} catch (IOException e) {
// ....
}
return jsonObject;
}
得到返回json即可。
// 素材下载接口:不支持视频文件的下载(GET)
private static final String DOWNLOAD_MEDIA = “http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s”;
使用String.format() 替换对应%s即可
这里直接将得到的相应输出到文件File中
/**
* 以http方式发送请求,并将请求响应内容输出到文件
*
* @param path
* 请求路径
* @param method
* 请求方法
* @param body
* 请求数据
* @return 返回响应的存储到文件
*/
public static File httpRequestToFile(String fileName, String path, String method, String body) {
if (fileName == null || path == null || method == null) {
return null;
}
File file = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
FileOutputStream fileOut = null;
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(method);
if (null != body) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(body.getBytes("UTF-8"));
outputStream.close();
}
inputStream = conn.getInputStream();
if (inputStream != null) {
file = new File(fileName);
} else {
return file;
}
// 写入到文件
fileOut = new FileOutputStream(file);
if (fileOut != null) {
int c = inputStream.read();
while (c != -1) {
fileOut.write(c);
c = inputStream.read();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
/*
* 必须关闭文件流 否则JDK运行时,文件被占用其他进程无法访问
*/
try {
inputStream.close();
fileOut.close();
} catch (IOException execption) {
execption.printStackTrace();
}
}
return file;
}