Gradle指令碼:上傳Apk到蒲公英

月光邊境發表於2018-05-21

一.建立app/pack-debug.gradle

import groovy.json.JsonSlurper

/**
 * 上傳apk到蒲公英
 */
def uploadApk() {
    //查詢上傳的apk檔案
    def apkDir = new File("build/outputs/apk/yyb/debug")
    if (!apkDir.exists()) {
        throw new RuntimeException("apk output path not exists!")
    }

    def apk = null
    for (int i = apkDir.listFiles().length - 1; i >= 0; i--) {
        File file = apkDir.listFiles()[i]
        if (file.name.endsWith(".apk")) {
            apk = file
            break
        }
    }
    if (apk == null) {
        throw new RuntimeException("apk file not exists!")
    }

    println "*************** start upload file ***************"

    def twoHyphens = "--"
    def boundary = "*********"
    def end = "\r\n"

    //模擬表單上傳 multipart/form-data
    def conn = new URL("https://www.pgyer.com/apiv2/app/upload").openConnection()
    conn.setRequestMethod('POST')
    conn.setRequestProperty("Connection", "Keep-Alive")
    conn.setRequestProperty("Charset", "UTF-8")
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary)
    conn.setDoInput(true)
    conn.setDoOutput(true)

    //新增引數:_api_key
    def sb = new StringBuilder()
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=_api_key")
    sb.append(end).append(end)
    sb.append("蒲公英api_key").append(end)

    //新增引數:buildUpdateDescription 更新日誌,取值gradle.properties中的 BUILD_NOTES
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=buildUpdateDescription")
    sb.append(end).append(end)
    sb.append(BUILD_NOTES).append(end)

    //新增引數file: 需要上傳的apk檔案
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=file;filename=").append(apk.getName())
    sb.append(end).append(end)

    def dos = new DataOutputStream(conn.getOutputStream())
    dos.writeBytes(sb.toString())
    dos.flush()
    sb.delete(0, sb.length())

    def fis = new FileInputStream(apk)
    byte[] bf = new byte[8192]
    int len
    while ((len = fis.read(bf)) != -1) {
        dos.write(bf, 0, len)
    }
    sb.append(end)
    sb.append(twoHyphens).append(boundary).append(end)
    dos.writeBytes(sb.toString())

    dos.flush()
    fis.close()
    dos.close()
    conn.connect()

    def text = conn.getContent().text
    def resp = new JsonSlurper().parseText(text)

    println text
    println "*************** upload finish ***************"

    if (resp.code != 0) {
        throw new RuntimeException(resp.message)
    }

    //瀏覽器中開啟短連線
    def url = "https://www.pgyer.com/" + resp.data.buildShortcutUrl
    exec {
        commandLine "powershell", "start", url
    }
}

//打包測試環境apk 上傳蒲公英 傳送郵件功能使用蒲公英自帶的郵件功能
task packageDebug {
    dependsOn("assembleYybDebug")

    doLast {
        uploadApk()
    }
}
複製程式碼

二:app/build.gradle中新增

apply from: 'pack-debug.gradle'
複製程式碼

三:執行gradlew packageDebug

相關文章