- package com.hyde.carelink2.wechat.utils;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.commons.httpclient.NameValuePair;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.mime.content.ByteArrayBody;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.hyde.carelink2.wechat.domain.upload.UploadImagResponse;
- import com.hyde.carelink2.wechat.service.wechat.WechatServerCenter;
- import com.hyde.common.StatusCode;
- import com.hyde.common.enums.ImageToken;
- import com.hyde.common.enums.ProjectType;
- import com.hyde.common.utils.HttpUtil;
- import com.hyde.config.enums.ConfigType;
- import com.hyde.config.impl.CommonConfig;
- /**
- * @author WangHuijie
- */
- public class DownloadImageUtil {
- private final static Logger LOGGER = LoggerFactory.getLogger(DownloadImageUtil.class);
- private static ObjectMapper objectMapper = new ObjectMapper();
- /**
- * 从微信服务器获取媒体文件
- *
- * @param param
- * @param mediaId
- * @param request
- * @return
- */
- public static Map < String,
- String > getImageFromWechat(String mediaId) {
- Map < String,
- String > map = new HashMap < String,
- String > ();
- String accessToken = ""; // 接口访问凭证
- try {
- accessToken = WechatServerCenter.getAccessToken();
- } catch(Exception e) {
- LOGGER.error(e.getMessage(), e);
- }
- String filePath = "";
- // 拼接请求地址
- String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
- try {
- URL url = new URL(requestUrl);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoInput(true);
- conn.setDoOutput(true);
- conn.setRequestMethod("GET");
- conn.setRequestProperty("Content-Type", "application/form-data");
- InputStream inputStream = conn.getInputStream();
- if (inputStream != null) {
- HttpURLConnection conn1 = (HttpURLConnection) url.openConnection();
- conn1.setDoInput(true);
- conn1.setDoOutput(true);
- conn1.setRequestMethod("GET");
- conn1.setRequestProperty("Content-Type", "application/form-data");
- InputStream inputStream1 = conn1.getInputStream();
- if (inputStream1 != null) {
- // 根据内容类型获取扩展名
- String contentType = conn1.getHeaderField("Content-Type");
- String expandName = getFileexpandedName(contentType);
- String fileName = mediaId + expandName;
- filePath = getUploadServerPath(inputStream1, contentType, fileName);
- map.put("path", filePath);
- map.put("code", String.valueOf(StatusCode.SUCCESS.getIndex()));
- map.put("msg", StatusCode.SUCCESS.getMessage());
- } else {
- map.put("code", String.valueOf(StatusCode.ERROR.getIndex()));
- map.put("msg", StatusCode.ERROR.getMessage());
- }
- } else {
- map.put("code", String.valueOf(StatusCode.ERROR.getIndex()));
- map.put("msg", StatusCode.ERROR.getMessage());
- }
- inputStream.close();
- conn.disconnect();
- } catch(Exception e) {
- LOGGER.error(e.getMessage(), e);
- }
- return map;
- }
- public static String getUploadServerPath(InputStream inputStream, String contentType, String fileName) {
- String filePath = null;
- byte[] bytes = new byte[0];
- try {
- bytes = toByteArray(inputStream);
- } catch(IOException e) {
- LOGGER.error(e.getMessage(), e);
- }
- String token = "DM5344d93e19c41adb5e0f5531bdd0336";
- ProjectType projectType = ProjectType.CARELINK2;
- ImageToken type = ImageToken.CARELINK2_USER_PORTRAIT;
- UploadImagResponse response = uploadImage(bytes, token, contentType, fileName, projectType, type);
- if (response != null) {
- filePath = response.getFilePath();
- }
- return filePath;
- }
- /**
- * 执行文件上传到图片服务器
- *
- * @param bytes
- * @param token
- * @param contentType
- * @param fileName
- * @param param
- * @return
- */
- protected static UploadImagResponse uploadImage(byte[] bytes, String token, String contentType, String fileName, ProjectType projectType, ImageToken type) {
- try {
- ByteArrayBody arrayBody = new ByteArrayBody(bytes, ContentType.create(contentType), fileName);
- List < NameValuePair > pairs = new ArrayList < NameValuePair > ();
- NameValuePair projectTypePair = new NameValuePair("p", String.valueOf(projectType.getIndex()));
- pairs.add(projectTypePair);
- NameValuePair typePair = new NameValuePair("type", String.valueOf(type.getIndex()));
- pairs.add(typePair);
- String url = CommonConfig.getConfig(ConfigType.UPLOAD_SERVICE_URL, String.class);
- String status = HttpUtil.postFile(url, arrayBody, token, pairs);
- UploadImagResponse response = objectMapper.readValue(status, UploadImagResponse.class);
- return response;
- } catch(Exception e) {
- LOGGER.error(e.getMessage(), e);
- }
- return null;
- }
- /**
- * 将输入流转为byte数组
- * @param input
- * @return
- * @throws IOException
- */
- public static byte[] toByteArray(InputStream input) throws IOException {
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- byte[] buffer = new byte[4096];
- int n = 0;
- while ( - 1 != (n = input.read(buffer))) {
- output.write(buffer, 0, n);
- }
- return output.toByteArray();
- }
- /**
- * 根据内容类型判断文件扩展名
- * @param contentType 内容类型
- * @return
- */
- public static String getFileexpandedName(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;
- }
- }
来源: http://www.bubuko.com/infodetail-2305655.html