AndroidでHTTP通信を行うサンプル
ついでにJsonからデータを取り出す。
OS:Android10
言語:kotlin
ライブラリ:okhttp
MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import java.io.IOException
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_sendSignUpInfo.setOnClickListener {
val client:OkHttpClient = OkHttpClient()
val url:String = "https://map.yahooapis.jp/dist/V1/distance?coordinates=139.73091159286,35.665662327613 135.49513388889,34.701974166667 130.42052944444,33.589735&appid=<APPID>"
val request = Request.Builder().url(url).build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
println("fail : $e")
}
override fun onResponse(call: Call, response: Response) {
var str = response!!.body!!.string()
Log.d("okhttp", "${str}")
val jsonObject = JSONObject(str)
val jsonArray = jsonObject.getJSONArray("Feature")
for (i in 0 until jsonArray.length()) {
val jsonData = jsonArray.getJSONObject(i)
val geometry = jsonData.getJSONObject("Geometry")
val distance = geometry.getDouble("Distance")
Log.d("okhttp", "$i : ${distance}")
}
}
})
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
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" />
<Button
android:id="@+id/btn_sendSignUpInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="163dp"
tools:layout_editor_absoluteY="404dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.takilab.httptest">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.takilab.httptest"
minSdkVersion 28
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.squareup.okhttp3:okhttp:4.4.0'
}
D/okhttp: {"ResultInfo":{"Count":1,"Total":1,"Start":1,"Latency":0.0,"Status":200,"Description":"\uFF12\u70B9\u9593\u306E\u7DEF\u5EA6\u7D4C\u5EA6\u3092\u6307\u5B9A\u3057\u3066\u5730\u7403\u306E\u6955\u5186\u4F53\u306B\u5408\u308F\u305B\u305F\u6B63\u78BA\u306A\u8DDD\u96E2\u3092\u53D6\u5F97\u3059\u308B\u6A5F\u80FD\u3092\u63D0\u4F9B\u3057\u307E\u3059\u3002","Copyright":"Copyright (C) 2020 Yahoo Japan Corporation. All Rights Reserved.","CompressType":""},"Feature":[{"Geometry":{"Type":"linestring","Distance":884.249118,"Geodesic":"true","Coordinates":"139.73091159286,35.665662327613 135.49513388889,34.701974166667 130.42052944444,33.589735"}}]}
D/okhttp: 0 : 884.249118