iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 21
0
Software Development

Kotlin 2018連續開發30天系列 第 21

Kotlin 2018連續開發30天 day 21 串接ptx api 下集

這邊重點 要導入的是import android.util.Base64 不是java用baase64

class HMAC_SHA1 {

@Throws(java.security.SignatureException::class)
fun Signature(xData: String, AppKey: String): String {
    try {

        // get an hmac_sha1 key from the raw key bytes
        val signingKey = SecretKeySpec(AppKey.toByteArray(charset("UTF-8")), "HmacSHA1")

        // get an hmac_sha1 Mac instance and initialize with the signing key
        val mac = Mac.getInstance("HmacSHA1")
        mac.init(signingKey)

        // compute the hmac on input data bytes
        val rawHmac = mac.doFinal(xData.toByteArray(charset("UTF-8")))
        val encoder = Base64.encode(rawHmac,Base64.DEFAULT).toString()
        return encoder

    } catch (e: Exception) {
        throw SignatureException("Failed to generate HMAC : " + e.message)
    }

}

}

回到主畫面

private fun getdata3() {

    var connection: HttpURLConnection? = null
    val APIUrl = "http://ptx.transportdata.tw/MOTC/APIs/v2/Rail/TRA/Station?\$top=10&\$format=JSON"
    //申請的APPID
    //(FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF 為 Guest 帳號,以IP作為API呼叫限制,請替換為註冊的APPID & APPKey)
    val APPID = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"
    //申請的APPKey
    val APPKey = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"

    //取得當下的UTC時間,Java8有提供時間格式DateTimeFormatter.RFC_1123_DATE_TIME
    //但是格式與C#有一點不同,所以只能自行定義
    val xdate = getServerTime()
    val SignDate = "x-date: $xdate"


    var Signature = ""
    try {
        //取得加密簽章
        Signature = HMAC_SHA1().Signature(SignDate, APPKey)
    } catch (e1: SignatureException) {
        // TODO Auto-generated catch block
        e1.printStackTrace()
    }


    println("Signature :$Signature")
    val sAuth = "hmac username=\"$APPID\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"$Signature\""
    println(sAuth)
    try {
        val url = URL(APIUrl)
        connection = url.openConnection() as HttpURLConnection
        connection!!.setRequestMethod("GET")
        connection!!.setRequestProperty("Authorization", sAuth)
        connection!!.setRequestProperty("x-date", xdate)
        connection!!.setRequestProperty("Accept-Encoding", "gzip")
        connection!!.setDoInput(true)
        connection!!.setDoOutput(true)

        //將InputStream轉換為Byte
        val inputStream = connection!!.getInputStream()
        val bao = ByteArrayOutputStream()
        val buff = ByteArray(1024)
        var bytesRead = inputStream.read(buff)
        while (bytesRead  != -1) {
            bao.write(buff, 0, bytesRead)
        }

        //解開GZIP
        val bais = ByteArrayInputStream(bao.toByteArray())
        val gzis = GZIPInputStream(bais)
        val reader = InputStreamReader(gzis)
        val `in` = BufferedReader(reader)

        //讀取回傳資料
        var line: String = `in`.readLine()
        var response = ""
        while (line != null) {
            response += line + "\n"
        }

        val RailStationListType = object : TypeToken<ArrayList<RailStation>>() {

        }.getType()
        val gsonReceiver = Gson()
        val obj = gsonReceiver.fromJson<Any>(response, RailStationListType)
        println(response)

    } catch (e: ProtocolException) {
        e.printStackTrace()
    } catch (e: Exception) {
        e.printStackTrace()
    }


}

這些是從PTX中範例資料改寫過來的 應該就可以使用 明天把它改寫成volley版本


上一篇
# Kotlin 2018連續開發30天 day20 語音轉文字
下一篇
Kotlin 2018連續開發30天 day21 發送信件
系列文
Kotlin 2018連續開發30天30

尚未有邦友留言

立即登入留言