生成公众号二维码

参考资料:https://blog.csdn.net/wrongyao/article/details/80250418

1.获取access_token

public static String getAccessToken(String appId,String appAecret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appAecret;
        Object result = HttpContenUtil.getURLGetContent(url);
        @SuppressWarnings("unchecked")
        Map<String, Object> openid  = (Map<String, Object>) JSONObject.parse(result.toString());
        
        return ObjectUtil.isEmpty(openid)?null:openid.containsKey("access_token")?openid.get("access_token").toString():null;
    }

2.获取ticket

3.获取二维码

工具类

package com.ry.finance.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import com.ry.finance.util.WXUtile.WXUtil;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

public class HttpContenUtil {
    /**
     * get方法访问
     *
     * @param urlStr
     * @return程序中访问http数据接口
     */
    public static Object getURLGetContent(String urlStr) {
        /** 网络的url地址 */
        URL url = null;
        /** http连接 */
        // HttpURLConnection httpConn = null;
        /**//** 输入流 */
        BufferedReader in = null;
        StringBuffer sb = new StringBuffer();
        try {
            url = new URL(urlStr);
            in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
            String str = null;
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
        } catch (Exception ex) {
            System.out.println("输入异常!");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                System.out.println("输出异常!");
            }
        }
//        String result = sb.toString();
//        JSONObject results = JSONObject.fromObject(result);
        // System.out.println(result);
//        return results;
        return sb;
    }
    
    /**
     * post 方法访问
     * 
     * @param urls
     * @param paraem
     * @return
     * @throws MalformedURLException
     */
    public static String getURLPostContent(String urls, String paraem) {

        String result = null;// 接收输出流

        // 要访问的url地址
        try {
            URL url = new URL(urls);

            // 连接访问地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 因为是post,所以用httpUrl接收
            // 设置参数 注意连接上后要先设置参数在做其他操作
            connection.setDoInput(true);// 向互联网读取数据,设置为true
            connection.setDoOutput(true);// 向互联网传递数据,设置为true
            connection.setUseCaches(false);
            connection.addRequestProperty("encoding", "UTF-8");
//             connection.addRequestProperty("Content-Type",
//             "application/www-form-urlencoded;charset=utf-8");
            // 设定使用方法 必须先设置参数在做其他
            connection.setRequestMethod("POST");
            // 输出流 将条件输入到请求地址 注意在请求的时候一定是先写入在写出
            OutputStream os = connection.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os,"utf-8");

            BufferedWriter bw = new BufferedWriter(osw);

            bw.write(paraem);// 对服务器输出
            bw.flush();
            bw.close();
            osw.close();
            os.close();

            // 获取到输入输出流 包装
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            // 输入
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                // 填充
                builder.append(line);
            }
            // 关闭流
            br.close();
            isr.close();
            is.close();
            result = builder.toString();
            System.out.println(result);
        } catch (MalformedURLException e) {
            System.out.println("连接失败!");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("数据导入异常");
            e.printStackTrace();
        }
        // 转换成json格式 返回回去
        return result;
    }
    
    /**
     * 带证书请求
     */
    public static String doRefundPost(String url,String xmlData) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
//        URL save = Thread.currentThread().getContextClassLoader().getResource("ftl/apiclient_cert.p12");
//        String str = save.toString();
        File file = ResourceUtils.getFile("classpath:ftl/apiclient_cert.p12");
        FileInputStream instream = new FileInputStream(file);//P12文件目录  写证书的项目路径
        try {
            keyStore.load(instream, WXUtil.MCHID.toCharArray());//这里写密码..默认是你的MCHID 证书密码
        } finally {
            instream.close();
        }
 
 
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, WXUtil.MCHID.toCharArray())//这里也是写密码的
                .build();
 
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {
            HttpPost httpost = new HttpPost(url); // 设置响应头信息
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(xmlData, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
 
                String returnMessage = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
                return returnMessage; //返回后自己解析结果
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
    
    /**
     * 上传二进制文件
     * @param graphurl 接口地址
     * @param file 图片文件
     * @return
     */
    public static String uploadFile(String graphurl,MultipartFile file) {
        String line = null;//接口返回的结果
        try {
            // 换行符
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            // 定义数据分隔线
            String BOUNDARY = "========7d4a6d158c9";
            // 服务器的域名
            URL url = new URL(graphurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST情
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
            OutputStream out = new DataOutputStream(conn.getOutputStream());
 
            // 上传文件
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            // 文件参数,photo参数名可以随意修改
            sb.append("Content-Disposition: form-data;name=\"image\";filename=\""
                    + "https://api.weixin.qq.com" + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 参数头设置完以后需要两个换行,然后才是参数内容
            sb.append(newLine);
            sb.append(newLine);
 
            // 将参数头的数据写入到输出流中
            out.write(sb.toString().getBytes());
 
            // 读取文件数据
            out.write(file.getBytes());
            // 最后添加换行
            out.write(newLine.getBytes());
 
            // 定义最后数据分隔线,即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
                    + boundaryPrefix + newLine).getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
            out.close();
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                return line;
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!" + e);
        }
        return line;
    }
    
    /**
     * 传递jsonhttp请求
     * @param url
     * @param json
     * @param fileName
     * @param targetPath
     * @return
     */
    public String httpPostWithJSON(String url, String json) {
        String result = "";
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;

        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            StringEntity se = new StringEntity(json);
            se.setContentType("application/json");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "UTF-8"));
            httpPost.setEntity(se);

            response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    InputStream instreams = resEntity.getContent();

                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}

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