微信公众号推送用户图片消息

业务大致逻辑:
1.授权获取code
2.通过code获取openid
3.上传图片到微信服务器获取mediaId
4.公众号推送图片到用户
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
   String backUri = "";
   String state = orid;
   backUri = URLEncoder.encode(backUri);
   String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
         + "appid="+ appid+ "&redirect_uri="+"xx.jsp"+ "&response_type=code&scope=snsapi_base&state="+state+"#wechat_redirect"+"&connect_redirect=1";
   resp.sendRedirect(url);
}
.action

String code=request.getParameter("code");
String filepath=WebContant.REALPATH+"/example/people.jpg";
   String access_token = WX_TokenUtil.getWXToken().getAccessToken();
    String openid= (String) getRequest().getSession().getAttribute("openid");
   if(openid==null||"".equals(openid)) {  //微信授权时会运行两次,第二次的openid为null(暂不知原因)  
      openid = WxSendPicUtil.getOpenId(code);
      getRequest().getSession().setAttribute("openid",openid);
   }
   String mediaId = WxSendPicUtil.upload(filepath, access_token, "image");
      WxSendPicUtil.sendPicOrVoiceMessageToUser(mediaId, openid, "image", access_token);
AccessToken 实体类
public class AccessToken implements Serializable {
    //获取到的凭证
    private String accessToken;
    //凭证有效时间,单位:秒
    private int expiresin;
    /**
     * @return the accessToken
     */
    public String getAccessToken() {
        return accessToken;
    }
    /**
     * @param accessToken the accessToken to set
     */
    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }
    /**
     * @return the expiresin
     */
    public int getExpiresin() {
        return expiresin;
    }
    /**
     * @param expiresin the expiresin to set
     */
    public void setExpiresin(int expiresin) {
        this.expiresin = expiresin;
    }
    public AccessToken() {
        // TODO Auto-generated constructor stub
    }

}
WxSendPicUtil类
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ectrip.android.bank.Alipay_Pay;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class WxSendPicUtil{
    public static final String appid = "wx0d872f39c7acfd63";
    public static final String secret = "d3b210bbc77749a9c500b86008a5522c";

    /**
     * 获得微信 AccessToken
     * access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。
     * 开发者需要access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取
     * 的access_token失效。
     * (此处我是把token存在Redis里面了)
     */

    public static AccessToken getWXToken() {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        JSONObject jsonObject = httpsRequest(tokenUrl, "GET", null);
        AccessToken access_token = new AccessToken();
        if (null != jsonObject) {
            try {
                access_token.setAccessToken(jsonObject.getString("access_token"));
                access_token.setExpiresin(jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                access_token = null;
                e.printStackTrace();
            }
        }

        return access_token;
    }

    //发送请求,根据code获取openId
    public static String getOpenId(String code) {
        String content = "";
        String openId = "";
        //封装获取openId的微信API
        StringBuffer url = new StringBuffer();
        url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
                .append(Alipay_Pay.readxmlparm("APPID"))
                .append("&secret=")
                .append(Alipay_Pay.readxmlparm("APPSECRET"))
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code")
                .append("&&connect_redirect=1");
        try {
            JSONObject jsonObject = httpsRequest(url.toString(), "GET", null);
            if (jsonObject.get("openid") != null)
                openId = jsonObject.get("openid").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return openId;
    }

    /**
     * 发送https请求
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String sendurl, String method, String str) {
        String myCharset = "UTF-8";
        String jsonStr = null;
        JSONObject jsonObject = null;
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        httpclient = HttpClients.createDefault();
        System.out.println("getOpenIdNew sendUrl:" +
                sendurl);
        if (!"GET".equals(method)) {
            return null;
        }
        HttpEntity entity = null;
        try {
            HttpGet httpGet = new HttpGet(sendurl);
            response = httpclient.execute(httpGet);
            entity = response.getEntity();
            if (entity != null) {
                jsonStr = EntityUtils.toString(entity, myCharset);
                jsonObject = JSONObject.parseObject(jsonStr);
                return jsonObject;
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 上传本地文件到微信获取mediaId
     */
    public static String upload(String filePath, String accessToken, String type) throws IOException {

        File file = new File(filePath);
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        String result = null;
        HttpURLConnection con;
        if (!file.exists() || !file.isFile()) {
            System.out.println("文件不存在");
        }
        try {
            //  String url = ConfigUtil.UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);
            String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=" + type;
            URL urlObj = new URL(url);
            //连接
            con = (HttpURLConnection) urlObj.openConnection();

            con.setRequestMethod("POST");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);

            //设置请求头信息
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");

            //设置边界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            StringBuilder sb = new StringBuilder();
            sb.append("--");
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");

            byte[] head = sb.toString().getBytes("utf-8");

            //获得输出流
            OutputStream out = new DataOutputStream(con.getOutputStream());
            //输出表头
            out.write(head);

            //文件正文部分
            //把文件已流文件的方式 推入到url中
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();

            //结尾部分
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定义最后数据分隔线

            out.write(foot);

            out.flush();
            out.close();
            //定义BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            if (result == null) {
                result = buffer.toString();
            }
        } catch (Exception e) {
            System.out.println("上传本地文件到微信异常e:" + e.getMessage());
            System.out.println("上传本地文件到微信获取mediaId异常:" + e);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(result);
        System.out.println(jsonObj);
        String typeName = "media_id";
        if (!"image".equals(type)) {
            typeName = type + "_media_id";
        }
        String mediaId = jsonObj.getString(typeName);
        return mediaId;
    }

    /**
     * 微信公共账号发送给账号(本方法限制使用的消息类型是语音或者图片)
     *
     * @param mediaId     图片或者语音内容
     * @param toUser      微信用户
     * @param messageType 消息类型
     * @return
     */

    public static void sendPicOrVoiceMessageToUser(String mediaId, String toUser, String msgType, String accessToken) {
        String json = null;
        if (msgType.equals("image")) {
            json = "{\"touser\": \"" + toUser + "\",\"msgtype\": \"image\", \"image\": {\"media_id\": \"" + mediaId + "\"}}";
        } else if (msgType.equals("voice")) {
            json = "{\"touser\": \"" + toUser + "\",\"msgtype\": \"voice\", \"voice\": {\"media_id\": \"" + mediaId + "\"}}";
        }
        //获取请求路径
        String action = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
        try {
            connectWeiXinInterface(action, json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接请求微信后台接口
     *
     * @param action 接口url
     * @param json   请求接口传送的json字符串
     */

    public static void connectWeiXinInterface(String action, String json) {
        URL url;
        try {
            url = new URL(action);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            OutputStream os = http.getOutputStream();
            os.write(json.getBytes("UTF-8"));// 传入参数
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String result = new String(jsonBytes, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(result);
            Object msg = jsonObject.get("errmsg");
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

示例:

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值