====== Android アプリ開発 ======
[[start|一つ上へ]]
===== 導入 =====
===== Httpクライアント =====
==== 権限追加 ====
AndroidManifestに
を追加。
==== HTTP通信処理 ====
HttpURLConnectionを用いてHTTP通信を行う処理。
HttpTaskというクラスに処理を記載していく。
class HttpTask : AsyncTask() {
override fun doInBackground(vararg params: URL?): Boolean {
var httpURLConnection: HttpURLConnection? = null
val outputPath = "/storage/emulated/0/Download/output.mp4"
try {
val url = params[0] as URL
httpURLConnection = url.openConnection() as HttpURLConnection
httpURLConnection.connect()
val status = httpURLConnection.responseCode
if (status == HttpURLConnection.HTTP_OK) {
val dataInputStream = DataInputStream(httpURLConnection.inputStream)
val dataOutputStream = DataOutputStream(FileOutputStream(outputPath))
val buffer = ByteArray(4096)
var readByte = dataInputStream.read(buffer)
while (readByte != -1) {
dataOutputStream.write(buffer, 0, readByte)
readByte = dataInputStream.read(buffer)
}
dataInputStream.close()
dataOutputStream.close()
return true
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect()
}
}
return false
}
}