项目背景
工作中经常遇到打包最新版APK给测试人员,开始的时候需要每次手动打包,分发给不同的测试人员,很是麻烦,后来使用蒲公英进行托管apk,可是依然需要每次手动上传至蒲公英网站,何不干脆写个脚本自动化这些操作呢!并通知到钉钉群中相关测试和开发人员
经过一番努力,主要是百度和查看钉钉和蒲公英相关文档,终于实现了功能,而不用引入jenkins这个庞然大物,主要是增加了pack-debug.gradle文件,非常简单方便
ContentModel的数据格式主要可以参考
https://open-doc.dingtalk.com/microapp/serverapi2/qf2nxq
正常使用代码中的格式即可
_api_key可以在https://www.pgyer.com/doc/view/api#uploadApp中获得
代码东西不多,就是利用Android URLConnection 进行网络上传
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
class ContentModel{
String text
String title
String picUrl
String messageUrl
}
/**
* 上传apk到蒲公英
*/
def uploadApk() {
//查找上传的apk文件,这里需要换成自己apk路径
def apkDir = new File("./app/build/outputs/apk/MyDemo/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("你的apiKey").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("this is test").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)
}
println resp
//浏览器中打开短连接
def url = "https://www.pgyer.com/" + resp.data.buildShortcutUrl
exec {
commandLine "powershell", "start", url
}
sendMsgToDing(resp.data)
}
//打包测试环境apk 上传蒲公英 发送邮件功能使用蒲公英自带的邮件功能
task packageDebug {
def apkDir = new File("./app/build/outputs/apk/MyDemo/debug")
if(apkDir.exists() && apkDir.isDirectory()){
apkDir.deleteDir()
}
dependsOn("assembleDebug")
doLast {
uploadApk()
}
}
def sendMsgToDing(def data){
def conn = new URL("你的钉钉webhook机器人地址").openConnection()
conn.setRequestMethod('POST')
conn.setRequestProperty("Connection", "Keep-Alive")
conn.setRequestProperty("Content-type", "application/json;charset=UTF-8")
conn.setConnectTimeout(30000)
conn.setReadTimeout(30000)
conn.setDoInput(true)
conn.setDoOutput(true)
def dos = new DataOutputStream(conn.getOutputStream())
HashMap<String,Object> map = new HashMap<>()
map.put("msgtype", "link")
ContentModel contentModel = new ContentModel()
contentModel.text = "已经上传至蒲公英,可以下载使用了"+data.buildCreated
contentModel.title= "上传提醒"+data.buildVersion
contentModel.picUrl = data.buildQRCodeURL
contentModel.messageUrl= "https://www.pgyer.com/" + data.buildShortcutUrl
map.put("link",contentModel)
def json = JsonOutput.toJson(map)
println(json)
dos.writeBytes(json)
def input = new BufferedReader(new InputStreamReader(conn.getInputStream()))
String line =""
String result=""
while ((line = input.readLine()) != null) {
result += line
}
dos.flush()
dos.close()
input.close()
conn.connect()
println(result)
}
使用方法
由于我是将pack-debug.gradle放在工程根目录下,所以在app的gradle文件中需要进行引用,
apply plugin: 'com.android.application'
apply from: "${rootProject.rootDir}/pack-debug.gradle"
最后直接在命令行,运行脚本,如下
等待几分钟
钉钉群里即可收到通知
task编写及执行顺序,可以参考
https://blog.csdn.net/u010479969/article/details/50131491
注意一下
需要注册钉钉开发者,才能在群里看到机器人的图标,开始的时候,我找了半天