建议详细阅读:微信开放文档
Controller类:
import com.weixin.wxDemo.service.TemporaryMateriaService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.File;
/**
* @Auther: 抹茶冰冰冰
* @Date: 2020-04-02
* @Description:创建临时素材
**/
@Controller
@RequestMapping("/TemporaryMateriaUtil")
public class TemporaryMateriaController {
/**
* 临时素材-服务接口
*/
@Autowired
private TemporaryMateriaService temporaryMateriaService;
/**
* 创建临时素材
* @return
*/
@RequestMapping(value = "createTemporaryMateria",method = RequestMethod.POST)
public JSONObject createTemporaryMateria(JSONObject jsonObject){
String type =jsonObject.getString("type");
File file=(File)jsonObject.get("file");
return temporaryMateriaService.createTemporaryMateria(type,file);
}
/**
* 获取临时素材
* @return
*/
@RequestMapping(value = "getTemporaryMateria",method = RequestMethod.GET)
public JSONObject getTemporaryMateria(String mediaId,String type){
return temporaryMateriaService.getTemporaryMateria(mediaId,type);
}
}
Service类:
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.net.URI;
/**
* @Auther: 抹茶冰冰冰
* @Date: 2020-04-02
* @Description:临时素材-服务接口
**/
@Service
public class TemporaryMateriaService {
/**
* 创建临时素材的URL
*/
@Value("${weixin.createTemporaryMateriaUrl}")
private String createTemporaryMateriaUrl;
/**
* 获取临时素材的URL
*/
@Value("${weixin.getTemporaryMateriaUrl}")
private String getTemporaryMateriaUrl;
/**
* 获取accessToken - 服务接口
*/
@Autowired
private GetAccessTokenService getAccessTokenService;
/**
* 创建临时素材
*
* @param type 文件类型 (image、voice、video、thumb)
* @param file 文件
* @return
*/
public JSONObject createTemporaryMateria(String type, File file) {
//返回的JSON对象
JSONObject resultJSONObject = new JSONObject();
//每次调用接口前需获取accessToken
String accessToken = getAccessTokenService.getAccessToken();
if (StringUtils.isBlank(accessToken)) {
resultJSONObject.put("success", false);
resultJSONObject.put("msg", "accessToken获取不到");
return resultJSONObject;
}
//替换url中我们需要替换的变量
String newCreateTemporaryMateriaUrl = createTemporaryMateriaUrl.replace("TYPE", type).replace("ACCESS_TOKEN", accessToken);
try {
//创建POST请求,并把对象放到reqEntity里
URI uri = new URI(newCreateTemporaryMateriaUrl);
HttpPost post = new HttpPost(uri);
FileBody fileBody = new FileBody(file);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("media", fileBody).build();
post.setEntity(reqEntity);
//由于是form请求方式,需要设置表头
post.setHeader("Content-Type", "multipart/form-data; charset=utf-8");
//发送请求
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse responseMsg = httpClient.execute(post);
//获取响应消息
HttpEntity resultEntity = responseMsg.getEntity();
String messageDemo = EntityUtils.toString(resultEntity, "utf-8");
JSONObject message = JSONObject.fromObject(messageDemo);
System.out.println("message:" + message);
//获取mediaId
String mediaId = message.getString("media_id");
resultJSONObject.put("msg", "文件上传成功");
resultJSONObject.put("mediaId", mediaId);
} catch (Exception e) {
e.printStackTrace();
resultJSONObject.put("success", false);
resultJSONObject.put("msg", "文件上传失败");
}
return resultJSONObject;
}
/**
* 获取临时素材
*
* @param mediaId
* @return
*/
public JSONObject getTemporaryMateria(String mediaId, String type) {
JSONObject resultJSONObject = new JSONObject();
BufferedOutputStream bufferedOutputStream = null;
FileOutputStream fileOutputStream = null;
//每次调用接口前需获取accessToken
String accessToken = getAccessTokenService.getAccessToken();
if (StringUtils.isBlank(accessToken)) {
resultJSONObject.put("success", false);
resultJSONObject.put("msg", "accessToken获取不到");
return resultJSONObject;
}
try {
//修改url并发送get请求
String url = getTemporaryMateriaUrl.replace("MEDIA_ID", mediaId).replace("ACCESS_TOKEN", accessToken);
URI uri = new URI(url);
HttpGet httpGet = new HttpGet(uri);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse responseMsg = httpClient.execute(httpGet);
//获取响应消息
HttpEntity resultEntity = responseMsg.getEntity();
String messageStr = EntityUtils.toString(resultEntity, "utf-8");
//返回的内容的错误判断
if (messageStr.indexOf("errcode") > -1) {
resultJSONObject.put("success", false);
resultJSONObject.put("msg", "无效的媒体Id");
return resultJSONObject;
}
if ("image".equals(type)) {
//若为图片 则用流的方式写到文件里
byte messageArray[] = EntityUtils.toByteArray(resultEntity);
File file = new File("F:\\img\\" + mediaId + ".jpeg");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bufferedOutputStream.write(messageArray);
fileOutputStream.close();
bufferedOutputStream.close();
resultJSONObject.put("url", file.getPath());
} else if ("video".equals(type)) {
//若为视频 则返回了一个url
JSONObject messageObject = JSONObject.fromObject(messageStr);
String videoUrl = messageObject.getString("video_url");
resultJSONObject.put("url", videoUrl);
}
} catch (Exception e) {
e.printStackTrace();
resultJSONObject.put("msg", "程序异常");
return resultJSONObject;
}
resultJSONObject.put("msg", "获取成功");
return resultJSONObject;
}
}