前提・実現したいこと
MacOSのPCでlocalhostサーバーを立ててそこのAPIへリクエストを試みています。
エミュレーターではうまくいっていて、実機ではうまく行きません。
実機でうまくいかないのはどういうことなんでしょうか。
発生している問題・エラーメッセージ
java.net.ConnectException: Failed to connect to /172.21.*
該当のソースコード
kotlin
1package com.websarva.wings.android.test 2 3import android.content.Context 4import androidx.appcompat.app.AppCompatActivity 5import android.os.Bundle 6import android.util.Log 7import android.view.MotionEvent 8import android.view.View 9import android.widget.Button 10import android.widget.EditText 11import android.widget.LinearLayout 12import androidx.lifecycle.lifecycleScope 13import com.squareup.moshi.Moshi 14import kotlinx.coroutines.launch 15import okhttp3.OkHttpClient 16import retrofit2.Response 17import retrofit2.Retrofit 18import retrofit2.converter.moshi.MoshiConverterFactory 19import retrofit2.create 20import retrofit2.http.Body 21 22class MainActivity : AppCompatActivity() { 23 override fun onCreate(savedInstanceState: Bundle?) { 24 super.onCreate(savedInstanceState) 25 setContentView(R.layout.activity_main) 26 val t1 = findViewById<EditText>(R.id.t1e) 27 val t2 = findViewById<EditText>(R.id.t2e) 28 val t3 = findViewById<EditText>(R.id.t3e) 29 val t4 = findViewById<EditText>(R.id.t4e) 30 val t5 = findViewById<EditText>(R.id.t5e) 31 val t6 = findViewById<EditText>(R.id.t6e) 32 val t7 = findViewById<EditText>(R.id.t7e) 33 val t8 = findViewById<EditText>(R.id.t8e) 34 val btn = findViewById<Button>(R.id.btnSave) 35 btn.setOnClickListener { 36 val moshi = Moshi.Builder() 37 .add(ApplicationJsonAdapterFactory) 38 .build() 39 40 val retrofit = Retrofit.Builder() 41 .baseUrl("http://172.21.*:8080") 42 .addConverterFactory(MoshiConverterFactory.create(moshi)) 43 .build() 44 45 val api = retrofit.create<API>() 46 val device = Device( 47 t1.text.toString(), 48 t2.text.toString(), 49 t3.text.toString(), 50 t4.text.toString(), 51 t5.text.toString(), 52 t6.text.toString(), 53 t7.text.toString(), 54 t8.text.toString() 55 ) 56 lifecycleScope.launch { 57 api.postDevice(device) 58 } 59 } 60 } 61}
dependencies { implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.appcompat:appcompat:1.4.0' implementation 'com.google.android.material:material:1.4.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.2' implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.4.0" implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation("se.ansman.kotshi:api:2.7.0") kapt("se.ansman.kotshi:compiler:2.7.0") implementation 'com.squareup.retrofit2:converter-moshi:2.9.0' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' }
試したこと
エミュレータを使って10.0.2.2で実行したところうまくいきました。
Macのファイヤーウォールはオフにしています。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
あなたの回答
tips
プレビュー