企业微信调用token-userinfo-userdetails-code

1. HttpClientUtils 工具类:

package com.wxapp;

import java.io.BufferedReader;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * HttpClientUtils
 */
public class HttpClientUtils { /**
     * 日志工具
     */
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
    /**
     * 5分钟
     */
    public static final int MINUTE_FIVE = 300000;

    /**
     * 10分钟
     */
    public static final int MINUTE_TEN = 600000;

    /**
     * HttpClient
     */
    private static final HttpClient client = getInstance();
    /**
     * 让Httpclient支持https
     *
     * @return HttpClient
     */
    private static HttpClient getInstance() { X509TrustManager x509mgr = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) { } public void checkServerTrusted(X509Certificate[] xcs, String string) { } public X509Certificate[] getAcceptedIssuers() { return null;
            } };

        SSLContext sslContext = null;
        try { sslContext = SSLContext.getInstance(SSLConnectionSocketFactory.SSL);
            sslContext.init(null, new TrustManager[] { x509mgr }, null);
        } catch (Exception e) { logger.error("error to init httpclient", e);
        } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(400);// 客户端总并行链接最大数
        connManager.setDefaultMaxPerRoute(40); // 每个主机的最大并行链接数

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(connManager);
        httpClientBuilder.setSSLSocketFactory(sslsf);
        return httpClientBuilder.build();
    } public static final RequestConfig getDefaultTimeOutConfig() { return getTimeOutConfig(60000, 30000);
    } private static final RequestConfig getTimeOutConfig(int socketTimeout, int connectionTimeout) { return RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectionTimeout).build();
    } /**
     * Get方法查询
     */
    public static String getMethodGetResponse(String address) throws Exception { return getMethodGetResponse(address, getDefaultTimeOutConfig());
    } /**
     * Post方法查询
     */
    public static String getMethodPostResponse(String address, HttpEntity paramEntity) throws Exception { RequestConfig config = getDefaultTimeOutConfig();
        return getMethodPostResponse(address, paramEntity, config);
    } /**
     * 自定义超时的Get方法查询
     */
    public static String getMethodGetResponse(String address, int connectionTimeout, int socketTimeout) throws Exception { return getMethodGetResponse(address, getTimeOutConfig(socketTimeout, connectionTimeout));
    } /**
     * 自定义超时的Post方法
     */
    public static String getMethodPostResponse(String address, HttpEntity paramEntity, int connectionTimeout, int socketTimeout) throws Exception { RequestConfig config = getTimeOutConfig(socketTimeout, connectionTimeout);
        return getMethodPostResponse(address, paramEntity, config);
    } /**
     * Post Entity
     */
    public static byte[] getMethodPostBytes(String address, HttpEntity paramEntity) throws Exception { return getMethodPostContent(address, paramEntity, getDefaultTimeOutConfig());
    } /**
     * HttpClient get方法请求返回Entity
     */
    public static byte[] getMethodGetContent(String address) throws Exception { return getMethodGetContent(address, getDefaultTimeOutConfig());
    } /**
     * HttpClient Get方法请求数据
     */
    private static String getMethodGetResponse(String address, RequestConfig config) throws Exception { logger.info("Start Access Address(" + address + ") With Get Request");
        byte[] result = getMethodGetContent(address, config);
        return new String(result, "utf-8");
    } /**
     * HttpClient Post方法请求数据
     */
    private static String getMethodPostResponse(String address, HttpEntity paramEntity, RequestConfig config) throws Exception { logger.info("Begin Access Url(" + address + ") By Post");
        byte[] content = getMethodPostContent(address, paramEntity, config);
        String result = new String(content, "utf-8");
        logger.info("Response -> " + result);
        return result;

    } /**
     * HttpClient get方法请求返回Entity
     */
    private static byte[] getMethodGetContent(String address, RequestConfig config) throws Exception { HttpGet get = new HttpGet(address);
        try { logger.info("Start Access Address(" + address + ") With Get Request");
            get.setConfig(config);
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { int code = response.getStatusLine().getStatusCode();
                throw new RuntimeException("HttpGet Access Fail , Return Code(" + code + ")");
            } response.getEntity().getContent();
            return convertEntityToBytes(response.getEntity());
        } finally { if (get != null) { get.releaseConnection();
            } } } /**
     * Post Entity
     */
    private static byte[] getMethodPostContent(String address, HttpEntity paramEntity, RequestConfig config) throws Exception { HttpPost post = new HttpPost(address);
        try { if (paramEntity != null) { post.setEntity(paramEntity);
            } post.setConfig(config);
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { int code = response.getStatusLine().getStatusCode();
                throw new RuntimeException("HttpPost Request Access Fail Return Code(" + code + ")");
            } HttpEntity entity = response.getEntity();
            if (entity == null) { throw new RuntimeException("HttpPost Request Access Fail Response Entity Is null");
            } return convertEntityToBytes(entity);
        } finally { if (post != null) { post.releaseConnection();
            } } } /**
     * 转化返回为byte数组
     *
     *
     * @param entity
     * @return byte[]
     * @throws Exception
     */
    private static byte[] convertEntityToBytes(HttpEntity entity) throws Exception { InputStream inputStream = null;
        try { if (entity == null || entity.getContent() == null) { throw new RuntimeException("Response Entity Is null");
            } inputStream = entity.getContent();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) { out.write(buffer, 0, len);
            } out.flush();
            return out.toByteArray();
        } finally { if (inputStream != null) { inputStream.close();
            } } } /**
     * 发送消息工具
     * @param path
     * @param params
     * @return
     * @throws Exception
     */
    public static String post(String path,String params) throws Exception{ if(path.startsWith("https")){ return https(path,params);
        }else{ return http(path,params);
        } } public static String http(String path,String params) throws Exception{ HttpURLConnection httpConn=null;
        BufferedReader in=null;
        PrintWriter out=null;
        try { URL url=new URL(path);
            httpConn=(HttpURLConnection)url.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);

//发送post请求参数
            out=new PrintWriter(httpConn.getOutputStream());
            out.println(params);
            out.flush();

//读取响应
            if(httpConn.getResponseCode()==HttpURLConnection.HTTP_OK){ StringBuffer content=new StringBuffer();
                String tempStr="";
                in=new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                while((tempStr=in.readLine())!=null){ content.append(tempStr);
                } return content.toString();
            }else{ throw new Exception("请求出现了问题!");
            } } catch (IOException e) { e.printStackTrace();
        }finally{ in.close();
            out.close();
            httpConn.disconnect();
        } return null;
    } public static String https(String path,String params) throws Exception { String res = null;
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost(path);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(2000).build();// 设置请求和传输超时时间
        request.setConfig(requestConfig);
        StringEntity myEntity = new StringEntity(params, "UTF-8");
        try { request.setEntity(myEntity);
            CloseableHttpResponse response = client.execute(request);
            res = EntityUtils.toString(response.getEntity());
            return res;
        } catch (Exception e) { e.printStackTrace();
        } finally { if (client != null) { try { client.close();
                } catch (IOException e) { e.printStackTrace();
                } } } return null;
    } }

2.调用:

public static java.util.Map getuserinfo(com.cms.ajax.AjaxModel model) throws Exception {
        String code = (String) model.getValue("code");
        System.out.println("code= " +code);
        String user_ticket = null;
        if(code==null||code==""){
            Map resultMap = new LinkedHashMap();
            resultMap.put("result", "code=null");
            return resultMap;
        }
        //获取AccessToken并检测是否过期
        if (AccessTokenInfo.getAccessToken() == null || AccessTokenInfo.getAccessToken().equals("")) {
            String turk = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx3670d88&corpsecret=DaTGCxrRZFBSfLKw";
            net.sf.json.JSONObject acereuslt = net.sf.json.JSONObject
                    .fromObject(HttpClientUtils.getMethodGetResponse(turk));
            AccessTokenInfo.setAccessToken(acereuslt.getString("access_token"));
            System.out.println("access_token= " + AccessTokenInfo.getAccessToken());
        } 
        
        try {
            String infourl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + AccessTokenInfo.getAccessToken()+ "&code=" + code;
            System.out.println("infourl=" + infourl);
            String tresult = HttpClientUtils.getMethodGetResponse(infourl);
            net.sf.json.JSONObject tkjson = net.sf.json.JSONObject.fromObject(tresult);
            System.out.println("tkjson1= " + tkjson);
            user_ticket = tkjson.getString("user_ticket");
            System.out.println("user_ticket= " + user_ticket);
            
        } catch (Exception e) {
            // access_token过期重新获取
            String turk = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx36d688&corpsecret=DaTOrU0xrRZFBSfLKw";
            net.sf.json.JSONObject acereuslt = net.sf.json.JSONObject
                    .fromObject(HttpClientUtils.getMethodGetResponse(turk));
            AccessTokenInfo.setAccessToken(acereuslt.getString("access_token"));
            System.out.println("刷新access_token= " + AccessTokenInfo.getAccessToken());
            String infourl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + AccessTokenInfo.getAccessToken()+ "&code=" + code;
            System.out.println("infourl=" + infourl);
            String tresult = HttpClientUtils.getMethodGetResponse(infourl);
            net.sf.json.JSONObject tkjson = net.sf.json.JSONObject.fromObject(tresult);
            System.out.println("tkjson= " + tkjson);
            user_ticket = tkjson.getString("user_ticket");
            e.printStackTrace();
        }
        
        //获取手机号码
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=" + AccessTokenInfo.getAccessToken();
        net.sf.json.JSONObject jo = new JSONObject();
        jo.put("user_ticket", user_ticket);
        String result = HttpClientUtils.post(url, jo.toString());
        System.out.println(result);
        String mobile = net.sf.json.JSONObject.fromObject(result).getString("mobile");
        Map resultMap = new LinkedHashMap();
        resultMap.put("result", mobile);
        return resultMap;
    }

注意地方

//获取手机号码
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=" +
这里是post请求,但是url的参数形式必须写成?access_token=xxx,不能把access_token参数设置在post请求体的参数形式去请求,url的地址必须跟官方保持一致

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,001评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,210评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,874评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,001评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,022评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,005评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,929评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,742评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,193评论 1 309
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,427评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,583评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,305评论 5 342
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,911评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,564评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,731评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,581评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,478评论 2 352

推荐阅读更多精彩内容