[Android] Retrofit2 사용법

2022. 11. 27. 17:05·🍞 FrontEnd/Android

Retrofit2 설치


retrofit github에 들어가 코드를 복사해 안드로이드 스튜디오에 다운로드를 해준다.

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
}
 

GitHub - square/retrofit: A type-safe HTTP client for Android and the JVM

A type-safe HTTP client for Android and the JVM. Contribute to square/retrofit development by creating an account on GitHub.

github.com

 

다음으로 안드로이드는 기본적으로 앱에서 따로 권한을 받지 않는 이상 통신이 안 된다.

그래서 manifest 파일에 아래 코드를 추가해 권한 설정을 해줌으로써 통신을 할 수 있게 해준다.

<uses-permission android:name="android.permission.INTERNET" />

 

다음으로, Gson 라이브러리를 추가해줘야 Retrofit이 JSON 형태를 알아볼 수 있다.

사이트에 들어가면 Retrofit Configuration에 코드가 있으며 아까와 같은 버전으로 설치해준다.

dependencies {
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}

 

Retrofit

A type-safe HTTP client for Android and Java

square.github.io

 

ApiService.kt

package com.example.homework9

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface ApiService {
    @GET("app/users/email-check") // 맨 앞 / 빼고, 쿼리스트링 전까지만
    fun getCheckEmail(
        @Query("email") email: String
    ): Call<Response> // api 호출 Response 형태로 받을 예정
}

 

Response.kt

package com.example.homework9

data class Response(
    val isSuccess: Boolean,
    val code: Int,
    val message: String,
)

 

MainActivity.kt

package com.example.homework9

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.homework9.databinding.ActivityMainBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Retrofit 객체 생성
        // 웹 브라우저 창 열기
        val retrofit = Retrofit.Builder()
            .baseUrl("https://prodmp.eric-rc.shop/")
            // json 형태로 들어오면 Gson 라이브러리에서 우리가 사용할 수 있는 객체 형태로 바꿔준다.
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        // 어떤 주소를 입력
        val apiService = retrofit.create(ApiService::class.java)

        // 입력한 주소 중에 하나로 연결 시도
        // 네트워크 통신이다 보니 비동기적으로 작동해야 돼서 queue 에 넣는 것. 백그라운드에서 작동
        apiService.getCheckEmail("test@test.com").enqueue(object: Callback<Response> {
            // 응답 받았을 때
            override fun onResponse(call: Call<Response>, response: retrofit2.Response<Response>) {
                // 응답이 왔다고 항상 성공인지는 모름
                if (response.isSuccessful) {
                    val responseData = response.body()
                    // 데이터가 안 넘어올 수 있어서 체크
                    if(responseData != null) {
                        // 여기서 code 는 api 에서 보내주는 내부 code (서버 개발자가 정한 코드)
                        Log.d("Retrofit", "Response\nCode: ${responseData.code} Message: ${responseData.message}")

                        if(responseData.code == 3001) {
                            Toast.makeText(this@MainActivity, "중복된 이메일입니다.", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
                // 응답이 왔지만 실패인 경우
                else {
                    // http 프로토콜 오류 code (전세계 규격 코드)
                    Log.w("Retrofit", "Response Not Successful ${response.code()}")
                }
            }
            // 서버와 연결을 실패했을 때
            override fun onFailure(call: Call<Response>, t: Throwable) {
                Log.e("Retrofit", "Error!", t)
            }
        })
    }
}

 

첫번째 결과값은 abc@abc.com 이메일을 체크한 결과를 출력한 것이며 code 값이 1001이다.

두번째 결과값은 test@test.com 이메일을 체크한 결과를 출력한 것이며 code 값은 3001이다.

저작자표시 (새창열림)

'🍞 FrontEnd > Android' 카테고리의 다른 글

[Android] 데이터 저장 방법 (SharedPreferences, RoomDB)  (0) 2022.11.20
[Android] Progress 타이머  (0) 2022.11.08
[Android] 앱 권한 요청 API level 오류  (0) 2022.11.02
[Android] 계산기 RoomDB  (0) 2022.10.31
[Android] 에뮬레이터에서 Toast 메세지가 안 보일 때  (0) 2022.10.31
'🍞 FrontEnd/Android' 카테고리의 다른 글
  • [Android] 데이터 저장 방법 (SharedPreferences, RoomDB)
  • [Android] Progress 타이머
  • [Android] 앱 권한 요청 API level 오류
  • [Android] 계산기 RoomDB
박빵이
박빵이
2025년에도 갓생살기
  • 박빵이
    기억보다 기록
    박빵이
  • 전체
    오늘
    어제
    • 분류 전체보기 (337)
      • 🍞 FrontEnd (97)
        • HTML+CSS (4)
        • JavaScript (17)
        • TypeScript (4)
        • React (52)
        • Next.js (2)
        • Android (15)
      • 🍞 BackEnd (24)
        • Java (15)
        • Node.js (6)
        • Spring (1)
      • 🍞 Cloud & Infra (0)
        • AWS SAA (0)
        • Microsoft Azure (0)
      • 🍞 Algorithm (147)
        • C++ (4)
        • Baekjoon (41)
        • Programmers (97)
      • 🍞 Computer Science (18)
        • 운영체제 (1)
        • 데이터 통신 (6)
        • 네트워크 (6)
        • 데이터베이스 (1)
      • 🍞 대외활동 & 부트캠프 (42)
        • 삼성 청년 SW 아카데미 (1)
        • LG유플러스 유레카 (0)
        • 한국대학생IT경영학회 (1)
        • IT연합동아리 UMC (17)
        • 길벗 블로깅 멘토 (18)
        • IT연합동아리 피로그래밍 (3)
        • 개발 컨퍼런스 (2)
  • 블로그 메뉴

    • Admin
  • 링크

    • GitHub
  • 인기 글

  • 태그

    코틀린
    위상정렬
    JavaScript
    코딩자율학습
    알고리즘
    안드로이드
    Android
    길벗 블로깅 멘토링
    길벗 블로깅 멘토
    Java
    프로그래머스
    백준
    C++
    react
    level1
    level2
    map
    umc
    유니온파인드
    Front
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
박빵이
[Android] Retrofit2 사용법
상단으로

티스토리툴바