3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android Kotlin HttpURLConnection Postできなくて困った話

Last updated at Posted at 2016-05-30

あち

HttpURLConnectionを使用してHTTP通信を行う
http://techbooster.jpn.org/andriod/application/6812/

こち

AndroidでPOSTリクエストを送付する(HttpURLConnection利用
http://qiita.com/kaikusakari/items/b1dd02803bb16956010a

に例が共有されているので楽勝だー、、と思っていたら予想外にハマったので共有

×な例

これだと接続されません。
なんでどぅわーー!

Main.kt
val task = object : AsyncTask<Void, Void, Void>() {
    override fun doInBackground(vararg params: Void): Void? {
        var con: HttpURLConnection? = null
        try {
            val urlStr = "http://hogehoge.jp/hoge"
            val param = "hoge=foo"
            val url = URL(urlStr)
            con = url.openConnection() as HttpURLConnection
            con.requestMethod = "POST"
            con.instanceFollowRedirects = false
            con.doOutput = true
            con.connect()       // これでつながるんじゃないの??

            val os = con.outputStream
            val ps = PrintStream(os)
            ps.print(param)
            ps.close()
        } catch (e: InterruptedException) {
        } finally {
            con?.disconnect()
        }

        return null
    }
}
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)

○な例

Main.kt
val task = object : AsyncTask<Void, Void, Void>() {
    override fun doInBackground(vararg params: Void): Void? {
        var con: HttpURLConnection? = null
        try {
            val urlStr = "http://hogehoge.jp/hoge"
            val param = "hoge=foo"
            val url = URL(urlStr)
            con = url.openConnection() as HttpURLConnection
            con.requestMethod = "POST"
            con.instanceFollowRedirects = false
            con.doOutput = true
            con.connect()       // これでつながるんじゃないの??

            val os = con.outputStream
            val ps = PrintStream(os)
            ps.print(param)
            ps.close()

            val responseCode = con.responseCode //ここで接続される
        } catch (e: InterruptedException) {
        } finally {
            con?.disconnect()
        }

        return null
    }
}
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)

というわけで投げっぱなしで良いとしても投げっぱなしはダメで、レスポンスを取得しないと接続されませんでした。
そういう仕様なんでしょうか?
情報持っている方いればプリーズ。

ちなみにAsyncTask#executeOnExecutorを使っているのは、executeだと複数のAsyncTaskがシングルスレッドで実行されるため、処理待ちでいつまで経っても実行順番が回ってこない事があるため。

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?