9
5

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.

Google Apps Script(GAS)でWebAPIを公開してAndroidから取得する

Posted at

# やりたいこと

実装

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <TextView
            android:id="@+id/result_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>
MainActivity.kt
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        fetch()
    }

    private fun fetch() {
        Thread(Runnable { // 非同期
            try {
                val url = URL("公開したWebAPIのurl?text=testes") // ?text=testes は query
                // queryは設定しなくても正常に "Please say something!" が返却される
                val urlConnection = url.openConnection() as HttpURLConnection
                urlConnection.requestMethod = "GET"
                urlConnection.connect()

                val sb = StringBuilder()
                val br = BufferedReader(InputStreamReader(urlConnection.inputStream))
                br.readLines().forEach {
                    sb.append(it)
                }
                br.close()

                println("result:$sb")
                runOnUiThread { // ui thread
                    result_text.text = sb.toString()
                }
            } catch (ex: Exception) {
                println("failure:$ex")
            }
        }).start()
    }
}

おわりに

ネイティブの実装が先に進んでてAPIが未完の時に使えるかと

9
5
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
9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?