Android retrofit 사용방법


Retrofit 2

github : https://github.com/square/retrofit

build.gradle (app)

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

    // optional
    implementation 'com.squareup.okhttp3:okhttp:3.12.0'
    // optional
    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.2'

}

manifest

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

통신에 사용될 데이터 모델 준비

별도 파일로

data json( //Json은 Key value형태이다. key = s, n 
    var s : String? =null,
    var n : Int? =null
)

interface 를 작성

interface APIS {

    @GET("요청 url")//Get Interface
    @Headers("accept: application/json",
            "content-type: application/json")
    fun get(
    ): Call<json>
		

    @POST("요청 url")//Post Interface
    @Headers("accept: application/json",
            "content-type: application/json")
    fun post(
            @Body jsonparams: json
    ): Call<json>

     companion object {// Retrofit 객체 초기화
        private const val BASE_URL = "통신할 주소"
        fun create(): APIS {

            val gson : Gson = GsonBuilder().setLenient().create()

            return Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build()
                    .create(APIS::class.java)
        }
    }
}

Call 에 대해서 import 자동 뜨는데, retrofit2 에 있는 걸로 선택하자.

interface ThirtyFitAPI {
    @Streaming
    @GET
    suspend fun downloadFile(@Url fileUrl:String): Call<ResponseBody>

    //@FormUrlEncoded
    //@Headers("accept: application/json", "content-type: application/json")
    @POST("kakao.php")
    fun informSignUp(
        @Body params: HashMap<String, String>,
    ): Call<ServerResponse>

    @POST("record.php")
    fun informActionRecord(
        @Body params: HashMap<String, String>,
    ): Call<ServerResponse>

    @POST("userinfo.php")
    fun informUserInfo(
        @Body params: HashMap<String, String>,
    ): Call<ServerResponse>

    @POST("fcm.php")
    fun informFCMtoken(
        @Body params: HashMap<String, String>,
    ): Call<ServerResponse>

    @POST("record.php")
    fun informMissionRecord(
        @Body params: HashMap<String, String>,
    ): Call<ServerResponse>

    @POST("record.php")
    fun informRecordAT(
        @Body params: HashMap<String, String>,
    ): Call<ServerResponse>

    @Multipart
    @POST("upload_profile.php")
    fun uploadProfile(
        @Part id: MultipartBody.Part,
        @Part file: MultipartBody.Part?): Call<ServerResponse>

    @POST("today_progress.php")
    fun todayProgress(
        @Body params: HashMap<String, String>
    ): Call<ServerResponse>

    @POST("joinout.php")
    fun informUnregister(
        @Query("uuid") uuid: String,
        @Query("origin") origin: Int
    ): Call<ServerResponse>

    @POST("app_report.php")
    fun sendReport(
        @Body params: HashMap<String, String>,
    ): Call<ServerResponse>

    @POST("unread_count.php")
    fun unreadCount(
        @Body params: HashMap<String, String>
    ): Call<ServerResponse>

    @Streaming
    @GET
    suspend fun downloadProfileImage(@Url fileUrl:String): Call<ResponseBody>
}

data class CommModel(
    var n: Int? = null,
    var s: String? = null
)

data class POST_TOKEN(
    val msgCode: String,
    val userUUID: String,
    val token: String
)


fun sendTokenToServer(token: String) {
        println("-------------------------------------------------- sendTokenToServer()")
        // prepare message
        val messageItem = POST_TOKEN("100", "a100100", token)
        val messageStr = Gson().toJson(messageItem)

        println("-------------------------------------------------- $messageStr")

        val api = APIS.create()
        val data: CommModel = CommModel(0, messageStr)

        api.post(data).enqueue(object : Callback<CommModel> {
            override fun onResponse(call: Call<CommModel>, response: Response<CommModel>) {
                // 200 or 404
                if(response.isSuccessful) { // 200
                    println("1 -------------------------------------------------- " + response.body().toString())
                    val data = response.body()
                    val receivedN = data!!.n
                    val receivedS = data!!.s

                    if (receivedN == 0) {
                        println("Post token success")
                    }
                    else {
                        println("something wrong")
                    }
                }
                else { // 404
                    println("2 -------------------------------------------------- 404")
                }
            }

            override fun onFailure(call: Call<CommModel>, t: Throwable) {
                //
                println("3 -------------------------------------------------- onFailure()")
            }
        })
    }

retrofit 에 헤더 조작 방법

보통 아래처럼 retofit 을 가져오는데,

val retrofit = Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build()

Interceptor 라는 것을 통해서 헤더에 조작을 할 수 있다.

fun getApiClient(): Retrofit {
        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(provideOkHttpClient(AppInterceptor()))
            .addConverterFactory(GsonConverterFactory.create())
            .build()

    }

    private fun provideOkHttpClient(interceptor: AppInterceptor): OkHttpClient
        = OkHttpClient.Builder().run {
            addInterceptor(interceptor)
            build()
        }

    class AppInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain) : Response = with(chain) {
            val newRequest = request().newBuilder()
                .addHeader("Accept-Language", Utils.getTopLocale())
                .build()
            proceed(newRequest)
        }
    }

사용할 때는 아래처럼

val retrofit = ApiClient.getApiClient()

        val api = retrofit.create(ThirtyFitAPI::class.java)
        val body = HashMap<String, Any>()
        body.put("eMail", eMail)
        body.put("identifier", identifier)
        body.put("signUpMethod", signUpMethod)
        println("identi ${identifier}")
        val call = api.setNotification(body)
,

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다