本人自己开发小程序遇到的坑,分享给大家,避免浪费大量时间
/**
* 微信文件上传接口
* @param file 待上传文件的完整路径
*/
public FileUploadOrDownload uploadTempMedia(String file) {
//设置消息请求头
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("multipart/form-data;charset=UTF-8");//multipart/form-data text/plain
headers.setContentType(type);
FileSystemResource resource = new FileSystemResource(new File(file));
//将文件作为参数添加
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("resource", resource);
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
// 获取accesstoken(这是我封装的accesstoken实体对象,可根据具体情况自行获取accesstoken)
AccessToken accesstoken = iAccessTokenDao.find("smallProgram");
String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+accesstoken.getAccess_token()+"&type=image";
RestTemplate restTemplate = new RestTemplate();
// 进行网络请求,访问url接口
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
// 解析返回值(返回json)
if (responseEntity!=null&&responseEntity.getStatusCode()==HttpStatus.OK) {
String sessionData = responseEntity.getBody();
FileUploadOrDownload result = JSON.parseObject(sessionData, FileUploadOrDownload.class);
return result;
} else {
return null;
}
}
/**
* 微信文件下载接口
* @param media_id 多媒体id
*/
@Override
public String getTempMedia(String media_id) {
// 获取accesstoken(可根据情况自行获取accesstoken)
AccessToken accesstoken = iAccessTokenDao.find("smallProgram");
String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+accesstoken.getAccess_token()+"&media_id="+media_id;
RestTemplate restTemplate = new RestTemplate();
// 进行网络请求,访问url接口
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class);
// 解析返回值(请求成功返回图片二进制流,失败返回错误信息json)
if (responseEntity!=null&&responseEntity.getStatusCode()==HttpStatus.OK) {
byte[] sessionData = responseEntity.getBody();
try {
for (int i = 0; i<sessionData.length; ++i) {
if (sessionData[i]<0) {// 调整异常数据
sessionData[i] += 256;
}
}
// 生成jpg图片
String savePath = "C:/Users/Administrator/Desktop";// 新生成的图片
if (!savePath.endsWith("/")) {
savePath += "/";
}
// 根据内容类型获取扩展名
String fileExt = responseEntity.getHeaders().getContentType().getSubtype();
// 将mediaId作为文件名
String filePath = savePath + media_id + "." + fileExt;
OutputStream out = new FileOutputStream(filePath);
out.write(sessionData);
out.flush();
out.close();
return filePath;
} catch (Exception e) {
throw new WxPreWebBaseException("", "解析异常", "解析微信小程序下载图片异常", e);
}
} else {
return null;
}
}