微信网页开发获取token,下载微信服务器上的临时图片

由于关联东西较多,我特意把方法从工具类提出来,放到了一个文件中,方便各位参考:


package com.vk.updoc.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.MimeTypeUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * TODO 微信网页开发,1.下载wx.chooseImage的图片到服务器磁盘,2.获取token
 * @author yqwang0907
 * @date 2018年5月8日下午4:28:08
 */
public class T {
	public static final String REDIS_CGI_BIN_TOKEN = "REDIS_CGI_BIN_TOKEN";//#获取token后存redis 7100

	/**上传服务器根目录 D:/*/
	private String sysdir;
	/**上传到根目录的某个文件夹*/
	private String projectDir;
	/**
	 * TODO 从微信服务器下载图片到服务器v2
	 * @param mediaId
	 * @return 磁盘绝对路径
	 * @author yqwang0907
	 * @date 2018年5月7日上午11:24:44
	 */
	public void downFileWxImg(String mediaId) {
		try {
			//获取token的地址=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}
			String accessToken = getToken();//这里先需要获取token
			//WxConfig.downMediaUrl=
			//下载地址
			String url = MessageFormat.format("https://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", accessToken,mediaId);
			
			String relativePath = projectDir + getAttachPath();// projectDir+/upload/yyyy/mm/
			
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpClient client = HttpClients.createDefault();
			HttpResponse resp = client.execute(httpGet);
			if (resp.getStatusLine().getStatusCode() == 200) {
				String size = resp.getFirstHeader("Content-Length").getValue();
				System.out.println(MessageFormat.format("文件大小{0}", size));
				String contentType = resp.getFirstHeader("Content-Type").getValue();
				
				String fileType = ".jpg";
				if (contentType.equals(MimeTypeUtils.IMAGE_JPEG_VALUE)) {
					fileType = ".jpg";
				} else if (contentType.equals(MimeTypeUtils.IMAGE_PNG_VALUE)) {
					fileType = ".png";
				} else if (contentType.equals(MimeTypeUtils.IMAGE_GIF_VALUE)) {
					fileType = ".gif";
				}
				String filename = UUID.randomUUID().toString() + fileType;
				//最终存储路径:
				String path = sysdir + relativePath + filename;
				//存到磁盘
				if (!(new File(path)).exists()) {
					(new File(path)).createNewFile();
				}
				FileCopyUtils.copy(resp.getEntity().getContent(), new FileOutputStream(path));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * TODO 获取token
	 * @author yqwang0907
	 * @date 2018年5月7日上午10:16:57
	 */
	public static String getToken(){
		String token = "";
		try {
			//【如果有redis】,建议先从redis中取:RedisCacheUtil objRedis
			/*Object o = objRedis.get(REDIS_CGI_BIN_TOKEN);
			if(o != null){
				token = StringUtils.trimToEmpty(o.toString());
			}
			if(!StringUtils.isEmpty(token)){
				return token;
			}*/
			
			String secret = "appSecret";//这里需要写自己的!!!
			String appid = "appId";//这里需要写自己的!!!
			//wx.token.url=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}
			String url = MessageFormat.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid,secret);
			String resultStr = request("GET", url, null);
			
			JSONObject jo = JSON.parseObject(resultStr);
			token = StringUtils.trimToEmpty(jo.getString("access_token"));
			
			if(StringUtils.isEmpty(token)){
				throw new Exception("获取token失败");
			}
			//存入token
			/*【如果有redis】objRedis.set(REDIS_CGI_BIN_TOKEN, token,7100);*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		return token;
	}
	/**
	 * TODO 获取动态的附件存放目录
	 * @return /upload/updoc_wx/yyyy/mm/
	 */
	public static String getAttachPath(){
		StringBuilder relativePath = new StringBuilder();
		Calendar c = Calendar.getInstance();
		relativePath.append("/upload/").append(c.get(Calendar.YEAR)).append("/").append(c.get(Calendar.MONTH)+1).append("/");//uid + "" + c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH)+1)+ "/";
		return relativePath.toString();
	}
	
	/**
	 * TODO 
	 * @param method [POST|GET]
	 * @param httpUrl 接口
	 * @param httpArg 参数
	 * @return 
	 * 2016年8月3日 下午10:33:53
	 * @throws Exception 
	 */
	public static String request(String method,String httpUrl, String httpArg){
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl+(StringUtils.isEmpty(httpArg)?"":"?"+httpArg);
	    if(StringUtils.isEmpty(method)){
	    	method = "GET";//默认get请求
	    }
	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setRequestMethod(method.toUpperCase());
	        connection.setConnectTimeout(10000);
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	    return result;
	}
}
注意:请自行修改参数secret、appId;代码供参考,可变通

你可能感兴趣的:(微信网页开发,java)