1. 程式人生 > >SpringBoot開發微信公眾號(六)

SpringBoot開發微信公眾號(六)

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

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

class HttpGet {
    protected static final int SOCKET_TIMEOUT = 10000; // 10S
    protected static final String GET = "GET";

    public static String get(String host, Map<String, String> params) {
        try {
            // 設定SSLContext
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);

            String sendUrl = getUrlWithQueryString(host, params);

            // System.out.println("URL:" + sendUrl);

            URL uri = new URL(sendUrl); // 建立URL物件
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
            if (conn instanceof HttpsURLConnection) {
                ((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
            }

            conn.setConnectTimeout(SOCKET_TIMEOUT); // 設定相應超時
            conn.setRequestMethod(GET);
            int statusCode = conn.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK) {
                System.out.println("Http錯誤碼:" + statusCode);
            }

            // 讀取伺服器的資料
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            
            String text = builder.toString();

            close(br); // 關閉資料流
            close(is); // 關閉資料流
            conn.disconnect(); // 斷開連線

            return text;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getUrlWithQueryString(String url, Map<String, String> params) {
        if (params == null) {
            return url;
        }

        StringBuilder builder = new StringBuilder(url);
        if (url.contains("?")) {
            builder.append("&");
        } else {
            builder.append("?");
        }

        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) { // 過濾空的key
                continue;
            }

            if (i != 0) {
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(encode(value));

            i++;
        }

        return builder.toString();
    }

    protected static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 對輸入的字串進行URL編碼, 即轉換為%20這種形式
     * 
     * @param input 原文
     * @return URL編碼. 如果編碼失敗, 則返回原文
     */
    public static String encode(String input) {
        if (input == null) {
            return "";
        }

        try {
            return URLEncoder.encode(input, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return input;
    }

    private static TrustManager myX509TrustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

}

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5編碼相關的類
 * 
 * @author wangjingtao
 * 
 */
public class MD5 {
    // 首先初始化一個字元陣列,用來存放每個16進位制字元
    private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**
     * 獲得一個字串的MD5值
     * 
     * @param input 輸入的字串
     * @return 輸入字串的MD5值
     * 
     */
    public static String md5(String input) {
        if (input == null)
            return null;

        try {
            // 拿到一個MD5轉換器(如果想要SHA1引數換成”SHA1”)
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 輸入的字串轉換成位元組陣列
            byte[] inputByteArray = input.getBytes("utf-8");
            // inputByteArray是輸入字串轉換得到的位元組陣列
            messageDigest.update(inputByteArray);
            // 轉換並返回結果,也是位元組陣列,包含16個元素
            byte[] resultByteArray = messageDigest.digest();
            // 字元陣列轉換成字串返回
            return byteArrayToHex(resultByteArray);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 獲取檔案的MD5值
     * 
     * @param file
     * @return
     */
    public static String md5(File file) {
        try {
            if (!file.isFile()) {
                System.err.println("檔案" + file.getAbsolutePath() + "不存在或者不是檔案");
                return null;
            }

            FileInputStream in = new FileInputStream(file);

            String result = md5(in);

            in.close();

            return result;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String md5(InputStream in) {

        try {
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");

            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = in.read(buffer)) != -1) {
                messagedigest.update(buffer, 0, read);
            }

            in.close();

            String result = byteArrayToHex(messagedigest.digest());

            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String byteArrayToHex(byte[] byteArray) {
        // new一個字元陣列,這個就是用來組成結果字串的(解釋一下:一個byte是八位二進位制,也就是2位十六進位制字元(2的8次方等於16的2次方))
        char[] resultCharArray = new char[byteArray.length * 2];
        // 遍歷位元組陣列,通過位運算(位運算效率高),轉換成字元放到字元陣列中去
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }

        // 字元陣列組合成字串返回
        return new String(resultCharArray);

    }

}


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;


public class TransApi {
	//百度翻譯的介面地址
    private static final String TRAN_API_URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    //百度翻譯開發者appid
    private static final String APP_ID = "你自己的app_Id";
    //開發者祕鑰
    private static final String SECURITY_KEY = "你自己的祕鑰"; 
    //翻譯源自動識別
    private static final String FROM = "auto";
    //翻譯結果語言 自動識別
    private static final String TO  ="auto";
    /**
     * 獲取翻譯結果
     * @param query
     * @return
     */
    public static String getTransResult(String query) {
        Map<String, String> params = buildParams(query);
        String resultMap = HttpGet.get(TRAN_API_URL, params);
        JSONObject json = JSONObject.fromObject(resultMap);
        StringBuffer buffer = new StringBuffer();
        //儲存翻譯後的結果
        List<Map> list = (List<Map>) json.get("trans_result");
        for (int i = 0; i < list.size(); i++) {
			buffer.append(list.get(i).get("dst"));
		}
        return buffer.toString(); 
    }

    private static  Map<String, String> buildParams(String query) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", FROM);
        params.put("to", TO);

        params.put("appid", APP_ID);

        // 隨機數
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 簽名
        String src = APP_ID + query + salt + SECURITY_KEY; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

}

三、測試