前提
Android Studioでkotlinを用いてAWSLambdaで作成したRestAPIと接続したいです。
その際にエラーコードが出ないものの、接続できないという問題が発生しました。
実現したいこと
Retrofit2を用いてAPIに接続できるようにする。
発生している問題・エラーメッセージ
ログを確認するとokEというログまでは出るのですが、okGが出ないため、val questionApiResponse = service.fetchQuestion().execute().body()?: throw IllegalStateException("body is null")の文が悪さをしているとは思うのですが、解決できませんでした。
該当のソースコード
TOinfo.kt
1data class QuestionInfo( 2 val answer: String, 3 val choice: Choice, 4 val num: Int, 5 val question: String 6) 7 8data class Choice( 9 val choiceA: String, 10 val choiceB: String, 11 val choiceC: String 12)
TOservice.kt
1interface QuestionService{ 2 @GET("/dev/question") 3 fun fetchQuestion(): retrofit2.Call<QuestionInfo> 4 5}
APIModel.kt
1class ApiModel : AppCompatActivity(){ 2 fun fetchApiQuestion() { 3 4 val moshi = Moshi.Builder() 5 .add(KotlinJsonAdapterFactory()) 6 .build() 7 8 val retrofit = Retrofit.Builder() 9 .baseUrl("https://hogehoge.com/") 10 .addConverterFactory(MoshiConverterFactory.create(moshi)) 11 .build() 12 13 14 thread{ 15 try { 16 val service: QuestionService = retrofit.create(QuestionService::class.java) 17 Log.d("msg","okE") 18 val questionApiResponse = service.fetchQuestion().execute().body() 19 ?: throw IllegalStateException("body is null") 20 Log.d("msg","okG") 21 22 Handler(Looper.getMainLooper()).post { 23 val qtext = questionApiResponse.toString() 24 Log.d("response", questionApiResponse.toString()) 25 } 26 27 }catch (e: Exception) { 28 Log.d("response-TO", "debug $e") 29 } 30 } 31 32 } 33}
回答2件
あなたの回答
tips
プレビュー