ユーザ用ツール

サイト用ツール


andloid

Android アプリ開発

導入

Httpクライアント

権限追加

AndroidManifestに

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

を追加。

HTTP通信処理

HttpURLConnectionを用いてHTTP通信を行う処理。 HttpTaskというクラスに処理を記載していく。

class HttpTask : AsyncTask<URL, Void, Boolean>() {

    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
    }
}
andloid.txt · 最終更新: 2023/05/17 17:22 by mikoto