【微信】——微信获取token及长链接转短链接

最近项目中接触到支付的部分,生成的链接用第三方的容易被微信屏蔽,所以使用微信官方的长链接转短链接的api,过程中需要获取微信token,关于获取token的知识网上很多,大家可自行百度。

WxUtils.java

public class WxUtils {

    /**
     * 微信根据APPID和APPSECRET获取token
     * @param appid  
     * @param appsrcret
     * @return 返回转换后的短链接
     */
    public static String getToken(String appid, String appsrcret) throws Exception {
        //访问地址
        String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        String APPID = appid;
        String APPSECRET = appsrcret;
        String request_url = TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        JSONObject jsonObject = HttpUtils.httpsUtil(request_url,"GET",null);
        if(null != jsonObject) {
            String access_token = jsonObject.getString("access_token");
            return access_token;
        }
        return null;
    }

    /**
     * 将长链接转为短链接(调用的微信短网址API)
     * 需要token
     * @param longUrl 需要转换的长链接url
     * @param appid
     * @param appsrcret
     * @return 返回转换后的短链接
     */
    public static ResultBean wxLongUrl2Short(String appid, String appsrcret, String longUrl) throws Exception {
        ResultBean result = new ResultBean<>();
        String token = getToken(appid, appsrcret);
        String uri = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";
        String url = uri.replace("ACCESS_TOKEN", token);
        String param = "{\"action\":\"long2short\","
                + "\"long_url\":\""+longUrl+"\"}";
        // 调用接口创建菜单
        JSONObject jsonObject = HttpUtils.httpRequest(url, "POST", param);
        System.out.println(jsonObject);
        if (null != jsonObject) {
            result.setCode(jsonObject.getInteger("errcode"));
            result.setData(jsonObject.getString("short_url"));
            return result;
        }else{
            return null;
        }
    }
    
}

HttpUtils.java

public class HttpUtils {

    /**
     * HttpsUtil方法https请求结果返回蔚json类型
     * @param Url http请求地址
     * @param Method http请求类型支持POST GET
     * @param Output
     * @return InputStream转换成JSONObject后返回
     * @throws Exception
     */
    public static JSONObject httpsUtil(String Url, String Method, String Output) throws Exception{
        JSONObject jsonObject = null;
        URL conn_url =  new URL(Url);
        HttpURLConnection conn = (HttpsURLConnection)conn_url.openConnection();
        conn.setRequestMethod(Method);
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.connect();
        //output获取access_token是不会用到
        if(Output != null){
            OutputStream outputstream =conn.getOutputStream();
            //字符集,防止出现中文乱码
            outputstream.write(Output.getBytes("UTF-8"));
            outputstream.close();
        }
        //正常返回代码为200
        if(conn.getResponseCode()==200){
            InputStream stream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(stream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            stream.close();
            conn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        }
        System.out.println(conn.getResponseCode());
        return jsonObject;
    }

    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)   {
        HttpsURLConnection httpUrlConn = null;
        OutputStream outputStream = null ;
        InputStream inputStream = null;

        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = { new MyX509TrustManager() };
        try{
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            httpUrlConn.connect();

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

            // 将返回的输入流转换成字符串
            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();
            jsonObject = JSONObject.parseObject(buffer.toString());
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            // 释放资源
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            inputStream = null;
            if (httpUrlConn != null ){
                httpUrlConn.disconnect();
            }
        }
        return jsonObject;
    }
}

 

你可能感兴趣的:(★JAVA学习之路★)