企业微信的一些方法

package com.sjzpicc.bi.web.quartz.controller;

/**
 * @Auther: zc
 * @Date: 2019/12/30 14:44
 * @Description:
 */

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

public class WorkWeixinUtil {
    public static String getUserID(String code, String accessToken) {
        if (StringUtils.isBlank(code)||StringUtils.isBlank(accessToken)) {
            return "none";
        } else {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + accessToken + "&code=" + code;
            String backData = WorkWeixinUtil.sendGet(url);
            String userID = (String) JSONObject.fromObject(backData).get("UserId");
            return userID;
        }
    }
    public static String getAccessTokenSs() {
        Properties properties = RepositoryReader.loadPropertyFromClasspath("application.properties");
        String corpid = properties.getProperty("corpid");
        String corpsecret = properties.getProperty("corpsecret");
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret;
        String backData = WorkWeixinUtil.sendGet(url);
        String accessToken = (String) JSONObject.fromObject(backData).get("access_token");
        System.out.println(accessToken);
        return accessToken;
    }
    public static String getJSApiTicketSs() {
        // 获取token
        String acess_token = WorkWeixinUtil.getAccessTokenSs();
        String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + acess_token;
        String backData = WorkWeixinUtil.sendGet(urlStr);
        String ticket = (String) JSONObject.fromObject(backData).get("ticket");
        return ticket;
    }
    public static String sendGet(String url) {
        String result = null;
        HttpGet httpRequst = new HttpGet(url);
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();// 设置请求和传输超时时间
            httpRequst.setConfig(requestConfig);
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);// 其中HttpGet是
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                result = EntityUtils.toString(httpEntity);// 取出应答字符串
                // 一般来说都要删除多余的字符
                result.replaceAll("\r", "");// 去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个小方格
            } else if (httpResponse.getStatusLine().getStatusCode() == 500) {
                httpRequst.abort();
                HttpGet httpRequstReload = new HttpGet(url);
                RequestConfig requestConfigReload = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();// 设置请求和传输超时时间
                httpRequstReload.setConfig(requestConfigReload);
                HttpResponse httpResponseReload = new DefaultHttpClient().execute(httpRequstReload);// 其中HttpGet是
                if (httpResponseReload.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntityReload = httpResponseReload.getEntity();
                    result = EntityUtils.toString(httpEntityReload);// 取出应答字符串
                    // 一般来说都要删除多余的字符
                    result.replaceAll("\r", "");// 去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个小方格
                } else {
                    httpRequstReload.abort();
                }
            } else {
                httpRequst.abort();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            result = e.getMessage().toString();
        } catch (IOException e) {
            e.printStackTrace();
            result = e.getMessage().toString();
        }
        return result;
    }

    /**
     * @method sendWechatmsgToUser
     * @描述: TODO(发送模板信息给用户)
     * @参数@param touser 用户的openid
     * @参数@param templat_id 信息模板id
     * @参数@param url 用户点击详情时跳转的url
     * @参数@param topcolor 模板字体的颜色
     * @参数@param data 模板详情变量 Json格式
     * @参数@return
     * @返回类型:String
     * @添加时间 2018-9-27 15:38:54
     */
    public static String sendWechatmsgToUser(String touser, String msgtype, String agentid,
                                             String content,String token) {
        String tmpurl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
//         token = getAccessTokenSs(); // 微信凭证,access_token
        String url = tmpurl.replace("ACCESS_TOKEN", token);
        JSONObject json = new JSONObject();
        try {
            json.put("touser", touser);
            json.put("msgtype", msgtype);
            json.put("agentid", agentid);
            JSONArray array=new JSONArray();
            JSONObject text=new JSONObject();
            text.put("content",content);
            array.add(text);
            json.put("text",text);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {

            int i = 1;
            while (i <= 3) {// 循环发送3次
                JSONObject resultJson = httpRequest(url, "POST", json.toString());
                String errmsg = (String) resultJson.get("errmsg");
                if ("ok".equals(errmsg)) { // 如果为errmsg为ok,则代表发送成功,公众号推送信息给用户了。
                    i = 4;
                    return "error";
                } else {
                    System.out.println("***************************微信返回的错误信息:" + errmsg);
                    i++;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "success";
    }
    /**
     *
     * @描述: TODO(发送http请求httpsRequest)
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.out.println("************************Weixin server connection timed out.");
        } catch (Exception e) {
            System.out.println("************************https request error:{" + e + "}");
        }
        return jsonObject;
    }

    public static void getUser(String token)
    {
        JSONObject get = httpRequest("https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN", "GET", "");//api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        System.out.println(get);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值