生成公眾號(hào)二維碼

參考資料: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數(shù)據(jù)接口
     */
    public static Object getURLGetContent(String urlStr) {
        /** 網(wǎng)絡(luò)的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();// 因?yàn)槭莗ost昌粤,所以用httpUrl接收
            // 設(shè)置參數(shù) 注意連接上后要先設(shè)置參數(shù)在做其他操作
            connection.setDoInput(true);// 向互聯(lián)網(wǎng)讀取數(shù)據(jù)郁稍,設(shè)置為true
            connection.setDoOutput(true);// 向互聯(lián)網(wǎng)傳遞數(shù)據(jù),設(shè)置為true
            connection.setUseCaches(false);
            connection.addRequestProperty("encoding", "UTF-8");
//             connection.addRequestProperty("Content-Type",
//             "application/www-form-urlencoded;charset=utf-8");
            // 設(shè)定使用方法 必須先設(shè)置參數(shù)在做其他
            connection.setRequestMethod("POST");
            // 輸出流 將條件輸入到請(qǐng)求地址 注意在請(qǐng)求的時(shí)候一定是先寫入在寫出
            OutputStream os = connection.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os,"utf-8");

            BufferedWriter bw = new BufferedWriter(osw);

            bw.write(paraem);// 對(duì)服務(wù)器輸出
            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);
            }
            // 關(guān)閉流
            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("數(shù)據(jù)導(dǎo)入異常");
            e.printStackTrace();
        }
        // 轉(zhuǎn)換成json格式 返回回去
        return result;
    }
    
    /**
     * 帶證書請(qǐng)求
     */
    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文件目錄  寫證書的項(xiàng)目路徑
        try {
            keyStore.load(instream, WXUtil.MCHID.toCharArray());//這里寫密碼..默認(rèn)是你的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); // 設(shè)置響應(yīng)頭信息
            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; //返回后自己解析結(jié)果
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
    
    /**
     * 上傳二進(jìn)制文件
     * @param graphurl 接口地址
     * @param file 圖片文件
     * @return
     */
    public static String uploadFile(String graphurl,MultipartFile file) {
        String line = null;//接口返回的結(jié)果
        try {
            // 換行符
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            // 定義數(shù)據(jù)分隔線
            String BOUNDARY = "========7d4a6d158c9";
            // 服務(wù)器的域名
            URL url = new URL(graphurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 設(shè)置為POST情
            conn.setRequestMethod("POST");
            // 發(fā)送POST請(qǐng)求必須設(shè)置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 設(shè)置請(qǐng)求頭參數(shù)
            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);
            // 文件參數(shù),photo參數(shù)名可以隨意修改
            sb.append("Content-Disposition: form-data;name=\"image\";filename=\""
                    + "https://api.weixin.qq.com" + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 參數(shù)頭設(shè)置完以后需要兩個(gè)換行籽腕,然后才是參數(shù)內(nèi)容
            sb.append(newLine);
            sb.append(newLine);
 
            // 將參數(shù)頭的數(shù)據(jù)寫入到輸出流中
            out.write(sb.toString().getBytes());
 
            // 讀取文件數(shù)據(jù)
            out.write(file.getBytes());
            // 最后添加換行
            out.write(newLine.getBytes());
 
            // 定義最后數(shù)據(jù)分隔線爱葵,即--加上BOUNDARY再加上--施戴。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
                    + boundaryPrefix + newLine).getBytes();
            // 寫上結(jié)尾標(biāo)識(shí)
            out.write(end_data);
            out.flush();
            out.close();
            // 定義BufferedReader輸入流來讀取URL的響應(yīng)
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                return line;
            }
        } catch (Exception e) {
            System.out.println("發(fā)送POST請(qǐng)求出現(xiàn)異常反浓!" + e);
        }
        return line;
    }
    
    /**
     * 傳遞jsonhttp請(qǐng)求
     * @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();
                }
            }
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市赞哗,隨后出現(xiàn)的幾起案子雷则,更是在濱河造成了極大的恐慌,老刑警劉巖肪笋,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件月劈,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡涂乌,警方通過查閱死者的電腦和手機(jī)艺栈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門英岭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來湾盒,“玉大人,你說我怎么就攤上這事诅妹》9矗” “怎么了?”我有些...
    開封第一講書人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵吭狡,是天一觀的道長尖殃。 經(jīng)常有香客問我,道長划煮,這世上最難降的妖魔是什么送丰? 我笑而不...
    開封第一講書人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮弛秋,結(jié)果婚禮上器躏,老公的妹妹穿的比我還像新娘。我一直安慰自己蟹略,他們只是感情好登失,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著挖炬,像睡著了一般揽浙。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上意敛,一...
    開封第一講書人閱讀 51,258評(píng)論 1 300
  • 那天馅巷,我揣著相機(jī)與錄音,去河邊找鬼草姻。 笑死钓猬,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的碴倾。 我是一名探鬼主播逗噩,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼掉丽,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了异雁?” 一聲冷哼從身側(cè)響起捶障,我...
    開封第一講書人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎纲刀,沒想到半個(gè)月后项炼,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡示绊,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年锭部,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片面褐。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡拌禾,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出展哭,到底是詐尸還是另有隱情湃窍,我是刑警寧澤,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布匪傍,位于F島的核電站您市,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏役衡。R本人自食惡果不足惜茵休,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望手蝎。 院中可真熱鬧榕莺,春花似錦、人聲如沸柑船。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽鞍时。三九已至亏拉,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間逆巍,已是汗流浹背及塘。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留锐极,地道東北人笙僚。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像灵再,于是被迫代替她去往敵國和親肋层。 傳聞我的和親對(duì)象是個(gè)殘疾皇子亿笤,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354