투케이2K

254. (kotlin/코틀린) [okhttp 4.9.0] [유틸 파일] RequestSyncGetHttp : get 방식 동기 http 요청 수행 본문

Kotlin

254. (kotlin/코틀린) [okhttp 4.9.0] [유틸 파일] RequestSyncGetHttp : get 방식 동기 http 요청 수행

투케이2K 2023. 4. 8. 20:55

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Kotlin

 

[소스 코드]

package com.example.kotlinproject

import okhttp3.*
import java.io.IOException
import java.util.concurrent.TimeUnit

class N_SyncHttp {


    /**
     * // --------------------------------------------------------------------------------------
     * TODO [클래스 설명]
     * // --------------------------------------------------------------------------------------
     * 1. 동기 네트워크 통신 수행 클래스
     * // --------------------------------------------------------------------------------------
     * 2. 필요 라이브러리 :
     *
     * [OK HTTP]
     * implementation("com.squareup.okhttp3:okhttp:4.9.0")
     *
     * [RX]
     * implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
     * implementation 'io.reactivex.rxjava3:rxkotlin:3.0.1'
     * implementation 'io.reactivex.rxjava3:rxjava:3.0.7'
     *
     * // --------------------------------------------------------------------------------------
     * */





    /**
     * // --------------------------------------------------------------------------------------
     * TODO [빠른 로직 찾기 : 주석 로직 찾기]
     * // --------------------------------------------------------------------------------------
     * // [SEARCH FAST] : [GET] : [QUERY STRING] : requestGetQueryStringHttp
     * // --------------------------------------------------------------------------------------
     */





    // --------------------------------------------------------------------------------------
    // TODO [companion object >> static 선언 실시]
    // --------------------------------------------------------------------------------------
    companion object {


        // ----------------------------------------------------------------------------------
        // TODO [전역 변수]
        // ----------------------------------------------------------------------------------
        val ACTIVITY_NAME = "N_SyncHttp"

        val RESPONSE_FLAG = "RESPONSE_FLAG"
        val RESPONSE_DATA = "RESPONSE_DATA"

        
    } // [companion 종료]





    // ----------------------------------------------------------------------------------
    // TODO [SEARCH FAST] : [GET] : [QUERY STRING] : requestGetQueryStringHttp
    // ----------------------------------------------------------------------------------
    /*
    try {
        // TODO [로딩 프로그레스 활성]
        C_Ui_View.startLoadingAlert(
            A_Intro@this,
            S_FinalMsg.AL_TITLE,
            "[HTTP] 요청 중 입니다. 잠시만 기다려 주세요.",
            S_FinalMsg.AL_OK)


        // TODO [새로운 스레드 생성 및 동기 요청 실시]
        val sync = Thread(Runnable {
            for(i in 1..5 step(1)) {

                // [URL 주소 선언]
                val url = "https://jsonplaceholder.typicode.com/posts"


                // [헤더 생성]
                val header: HashMap<String, Any> = HashMap()


                // [파라미터 생성]
                val params: HashMap<String, Any> = HashMap()
                params["userId"] = 1
                params["id"] = 1


                // [http 요청 수행]
                var requestSyncGetHttp = N_SyncHttp().RequestSyncGetHttp(url, header, params)
                requestSyncGetHttp.start()
                try {
                    requestSyncGetHttp.join()
                }
                catch (e : Exception) {
                    e.printStackTrace()
                }


                // [http 응답 확인]
                var response = requestSyncGetHttp.getResponse()
                S_Log.ltw("================================================")
                S_Log.cnt("[" + ACTIVITY_NAME + " >> "+C_Util.getNowMethod(1)+" :: [GET] HTTP 통신 수행 결과]")
                S_Log.cnt("-----------------------------------------")
                S_Log.cnt("[SUCCESS :: "+response.get(N_SyncHttp.RESPONSE_FLAG)+"]")
                S_Log.cnt("-----------------------------------------")
                S_Log.cnt("[DATA :: "+response.get(N_SyncHttp.RESPONSE_DATA)+"]")
                S_Log.lbw("================================================")

            }


            // TODO [로딩 프로그레스 종료]
            C_Ui_View.stopLoadingAlert(A_Intro@this)

        })
        sync.start() // [스레드 동작 수행]
    }
    catch (e : Exception) {
        e.printStackTrace()
    }
    */
    // ----------------------------------------------------------------------------------
    inner class RequestSyncGetHttp : Thread {

        // [변수 선언 실시]
        var url = ""
        var header = HashMap<String, Any>()
        var params = HashMap<String, Any>()


        // [http 요청 후 응답 값 리턴]
        var response = HashMap<String, Any>()


        // [클래스 생성자 초기화]
        constructor(url:String, header:HashMap<String, Any>, params:HashMap<String, Any>){
            this.url = url
            this.header = header
            this.params = params
        }


        // [http 수행 실시]
        override fun run(){
            super.run()
            try {
                // ------------------------------------------------------
                // TODO [URL 변수 선언 실시]
                var urlData = url
                // ------------------------------------------------------


                // ------------------------------------------------------
                //TODO [url 에 파라미터 추가 실시]
                if (C_Util.mapNotNull(params) === true) { // [파라미터가 있는 경우]

                    if (urlData.endsWith("?") == false) {
                        urlData = "$urlData?"
                    }

                    urlData = urlData + C_Util.mapToUrlEncodeQueryString(params)
                }
                // ------------------------------------------------------


                // ------------------------------------------------------
                //TODO [OK HTTP 객체 선언 실시]
                val client: OkHttpClient = OkHttpClient().newBuilder()
                    .connectTimeout(10, TimeUnit.SECONDS) // [커넥션 제한 시간]
                    //.readTimeout(10, TimeUnit.SECONDS)
                    //.writeTimeout(10, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(false)
                    .build()

                val request = Request.Builder()
                request.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8;") //TODO [헤더]
                request.addHeader("Cache-Control", "no-cache") //TODO [헤더]

                if (C_Util.mapNotNull(header) === true) {
                    val set = header.keys
                    val iterator = set.iterator()
                    while (iterator.hasNext()) {
                        val key = iterator.next() as String
                        request.addHeader(key, header[key].toString()) //TODO [헤더 추가]
                        S_Log.ltd("================================================")
                        S_Log.cnt("[" + ACTIVITY_NAME + " >> RequestSyncGetHttp :: OK HTTP 동기 GET [헤더] 추가]")
                        S_Log.cnt("-----------------------------------------")
                        S_Log.cnt("[KEY :: $key]")
                        S_Log.cnt("-----------------------------------------")
                        S_Log.cnt("[VALUE :: " + header[key].toString() + "]")
                        S_Log.lbd("================================================")
                    }
                }

                request.url(urlData) //TODO [urlData 추가]
                // ------------------------------------------------------


                // ------------------------------------------------------
                // TODO [요청 로그 출력 실시]
                S_Log.ltw("================================================")
                S_Log.cnt("[" + ACTIVITY_NAME + " >> RequestSyncGetHttp :: OK HTTP 동기 GET [요청] 실시]")
                S_Log.cnt("-----------------------------------------")
                S_Log.cnt("[TYPE :: GET >> REQUEST]")
                S_Log.cnt("-----------------------------------------")
                S_Log.cnt("[URL :: $urlData]")
                S_Log.cnt("-----------------------------------------")
                S_Log.cnt("[HEADER :: $header]")
                S_Log.cnt("-----------------------------------------")
                S_Log.cnt("[PARAMS :: $params]")
                S_Log.lbw("================================================")
                // ------------------------------------------------------


                // ------------------------------------------------------
                //TODO [비동기 처리 (enqueue 사용)]
                val finalUrlData = urlData

                //TODO [동기 처리 (execute 사용)]
                val response = client.newCall(request.build()).execute()
                if (response.isSuccessful){
                    val responseHeader = response.headers.toString()
                    val responseCode = response.code.toString()
                    val responseData = response.body!!.string()

                    S_Log.ltw("================================================")
                    S_Log.cnt("[" + ACTIVITY_NAME + " >> RequestSyncGetHttp :: OK HTTP 동기 GET [응답] 확인]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[TYPE :: GET >> RESPONSE]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[CODE :: $responseCode]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[URL :: $finalUrlData]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[HEADER :: $responseHeader]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[DATA :: $responseData]")
                    S_Log.lbw("================================================")

                    // ------------------------------------------------------
                    // TODO [응답 코드 값 체크 및 리턴 데이터 반환]
                    // ------------------------------------------------------
                    try {
                        val statusCode = response.code
                        if (statusCode >= 200 && statusCode < 300) { // TODO [정상 응답]

                            // ------------------------------------------------------
                            // TODO [응답 값 삽입]
                            // ------------------------------------------------------
                            this.response.put(RESPONSE_FLAG, true) // [플래그값 저장]
                            this.response.put(RESPONSE_DATA, responseData) // [메시지 삽입]
                        }
                        else { // TODO [에러 응답]

                            // ------------------------------------------------------
                            // TODO [응답 값 삽입]
                            // ------------------------------------------------------
                            this.response.put(RESPONSE_FLAG, false) // [플래그값 저장]
                            this.response.put(RESPONSE_DATA, "[ERROR] : [RequestSyncGetHttp] : " + C_Msg.getErrorHttpMsg(responseCode)) // [메시지 삽입]
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()

                        // ------------------------------------------------------
                        // TODO [응답 값 삽입]
                        // ------------------------------------------------------
                        this.response.put(RESPONSE_FLAG, false) // [플래그값 저장]
                        this.response.put(RESPONSE_DATA, "[EXCEPTION] : [0] : [RequestSyncGetHttp] : " + e.message.toString()) // [메시지 삽입]
                    }

                    // ------------------------------------------------------
                }
                else { // TODO [요청이 실패한 경우]
                    val responseHeader = response.headers.toString()
                    val responseCode = response.code.toString()
                    val responseData = response.body!!.string()

                    S_Log.lte("================================================")
                    S_Log.cnt("[" + ACTIVITY_NAME + " >> RequestSyncGetHttp :: OK HTTP 동기 GET [에러] 확인]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[TYPE :: GET >> FAIL]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[CODE :: $responseCode]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[URL :: $finalUrlData]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[HEADER :: $responseHeader]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[DATA :: $responseData]")
                    S_Log.lbe("================================================")

                    // ------------------------------------------------------
                    // TODO [응답 값 삽입]
                    // ------------------------------------------------------
                    this.response.put(RESPONSE_FLAG, false) // [플래그값 저장]
                    this.response.put(RESPONSE_DATA, "[EXCEPTION] : [1] : [RequestSyncGetHttp] : " + responseData) // [메시지 삽입]
                }
            }
            catch (e : Exception) {
                e.printStackTrace()
                S_Log.lte("================================================")
                S_Log.cnt("[" + N_AsyncHttp.ACTIVITY_NAME + " >> RequestSyncGetHttp :: OK HTTP 동기 GET [Exception] 확인]")
                S_Log.cnt("-----------------------------------------")
                S_Log.cnt("[TYPE :: GET >> EXCEPTION]")
                S_Log.cnt("-----------------------------------------")
                S_Log.cnt("[EXCEPTION :: " + e.message.toString() + "]")
                S_Log.lbe("================================================")

                // ------------------------------------------------------
                // TODO [응답 값 삽입]
                // ------------------------------------------------------
                this.response.put(RESPONSE_FLAG, false) // [플래그값 저장]
                this.response.put(RESPONSE_DATA, "[EXCEPTION] : [2] : [RequestSyncGetHttp] : " + e.message.toString()) // [메시지 삽입]
            }
        }


        // [http 요청 성공 및 슬패 결과 값 리턴 함수]
        fun getResponse(): Map<String, Any> {
            return this.response
        }

    }


} // TODO [클래스 종료]
 

[결과 출력]

 

W///===========//: ================================================
I/: [N_SyncHttp >> RequestSyncGetHttp :: OK HTTP 동기 GET [요청] 실시]
I/: -----------------------------------------
I/: [TYPE :: GET >> REQUEST]
I/: -----------------------------------------
I/: [URL :: https://jsonplaceholder.typicode.com/posts?id=1&userId=1]
I/: -----------------------------------------
I/: [HEADER :: {}]
I/: -----------------------------------------
I/: [PARAMS :: {id=1, userId=1}]
W///===========//: ================================================



W///===========//: ================================================
I/: [N_SyncHttp >> RequestSyncGetHttp :: OK HTTP 동기 GET [응답] 확인]
I/: -----------------------------------------
I/: [TYPE :: GET >> RESPONSE]
I/: -----------------------------------------
I/: [CODE :: 200]
I/: -----------------------------------------
I/: [URL :: https://jsonplaceholder.typicode.com/posts?id=1&userId=1]
I/: -----------------------------------------
I/: [HEADER :: date: Sat, 08 Apr 2023 11:47:57 GMT
    content-type: application/json; charset=utf-8
I/: -----------------------------------------
I/: [DATA :: [
      {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
      }
    ]]
W///===========//: ================================================



W///===========//: ================================================
I/: [A_Intro >> onCreate$lambda-1 :: [GET] HTTP 통신 수행 결과]
I/: -----------------------------------------
I/: [SUCCESS :: true]
I/: -----------------------------------------
I/: [DATA :: [
      {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
      }
    ]]
W///===========//: ================================================

 

반응형
Comments