101010

プログラミング備忘録とともに、ポエムってます。

HttpsURLConnectionを使ったHTTPリクエスト | Android Kotlin

HTTPリクエストはOkHttpで行うようにしていこうと思うが、せっかく作ったHttpsURLConnectionを捨ててしまうのももったいないのでこのページにプログラムコードを載せておくことにしよう。 PostParamsのようなクラスもわざわざ作ったが、OkHttpにはFormBody.Builder()なるものが既に存在している。

import java.io.IOException
import java.net.URL
import javax.net.ssl.HttpsURLConnection


fun fetchJojoApi(): String? = downloadUrl(JOJO_API)


fun fetchEchoApi(): String? {
    val params = PostParams()
    params["name"] = "ほげほげ"
    params["message"] = "こんにちは、世界!"
    params["response_type"] = "string"
    return downloadUrlPost(POST_ECHO_API, params)
}




const val ERROR = -1
const val CONNECT_SUCCESS = 0
const val GET_INPUT_STREAM_SUCCESS = 1
const val PROCESS_INPUT_STREAM_IN_PROGRESS = 2
const val PROCESS_INPUT_STREAM_SUCCESS = 3


@Throws(IOException::class)
private fun downloadUrl(httpsUrl: String): String? {

    var conn: HttpsURLConnection? = null
    return try {
        conn = (URL(httpsUrl).openConnection() as? HttpsURLConnection)
        conn?.run {
            readTimeout = 20000
            connectTimeout = 20000
            requestMethod = "GET"
            doInput = true
            connect()
            // CONNECT_SUCCESSをプログレスに通知できる
            if (responseCode != HttpsURLConnection.HTTP_OK) {
                throw IOException("HTTP error code: $responseCode")
            }
            // GET_INPUT_STREAM_SUCCESSをプログレスに通知できる
            inputStream?.use { stream ->
                stream.bufferedReader().use { it.readText() }
            }
        }
    } finally {
        conn?.disconnect()
    }
}


@Throws(IOException::class)
private fun downloadUrlPost(httpsUrl: String,
                            params: PostParams,
                            userAgent:String? = System.getProperty("http.agent")): String? {

    var conn: HttpsURLConnection? = null
    return try {
        conn = (URL(httpsUrl).openConnection() as? HttpsURLConnection)
        conn?.run {
            readTimeout = 20000
            connectTimeout = 20000
            requestMethod = "GET"
            doInput = true
            doOutput = true
            userAgent?.let { setRequestProperty("User-Agent", it) }
            setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
            connect()
            // CONNECT_SUCCESSをプログレスに通知できる

            outputStream?.use {
                it.write(params.toPostByteArray())
                it.flush()
            }

            if (responseCode != HttpsURLConnection.HTTP_OK) {
                throw IOException("HTTP error code: $responseCode")
            }
            // GET_INPUT_STREAM_SUCCESSをプログレスに通知できる
            inputStream?.use { stream ->
                stream.bufferedReader().use { it.readText() }
            }
        }
    } finally {
//        conn?.inputStream?.close()
        conn?.disconnect()
    }
}

class PostParams:HashMap<String, String>() {
    fun toPostByteArray(): ByteArray = this.map { (key, value) ->
        "$key=$value"
    }.joinToString(separator = "&").toByteArray()
}