투케이2K

274. (kotlin/코틀린) [유틸 파일] requestDeleteQueryStringHttp : delete 방식 동기식 http 요청 수행 실시 본문

Kotlin

274. (kotlin/코틀린) [유틸 파일] requestDeleteQueryStringHttp : delete 방식 동기식 http 요청 수행 실시

투케이2K 2023. 4. 21. 21:25

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Kotlin

 

[소스 코드]

    // ----------------------------------------------------------------------------------
    // TODO [SEARCH FAST] : [DELETE] : [QUERY STRING] : requestDeleteQueryStringHttp
    // ----------------------------------------------------------------------------------
    /*
    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/1"


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


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


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


                // [http 응답 확인]
                var response = requestSyncDeleteHttp.getResponse()
                S_Log.ltw("================================================")
                S_Log.cnt("[" + ACTIVITY_NAME + " >> "+C_Util.getNowMethod(1)+" :: [DELETE] 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 RequestSyncDeleteHttp : 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 + " >> RequestSyncDeleteHttp :: OK HTTP 동기 DELETE [헤더] 추가]")
                        S_Log.cnt("-----------------------------------------")
                        S_Log.cnt("[KEY :: $key]")
                        S_Log.cnt("-----------------------------------------")
                        S_Log.cnt("[VALUE :: " + header[key].toString() + "]")
                        S_Log.lbd("================================================")
                    }
                }

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


                // ------------------------------------------------------
                // TODO [요청 로그 출력 실시]
                S_Log.ltw("================================================")
                S_Log.cnt("[" + ACTIVITY_NAME + " >> RequestSyncDeleteHttp :: OK HTTP 동기 DELETE [요청] 실시]")
                S_Log.cnt("-----------------------------------------")
                S_Log.cnt("[TYPE :: DELETE >> 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 + " >> RequestSyncDeleteHttp :: OK HTTP 동기 DELETE [응답] 확인]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[TYPE :: DELETE >> 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] : [RequestSyncDeleteHttp] : " + C_Msg.getErrorHttpMsg(responseCode)) // [메시지 삽입]
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()

                        // ------------------------------------------------------
                        // TODO [응답 값 삽입]
                        // ------------------------------------------------------
                        this.response.put(RESPONSE_FLAG, false) // [플래그값 저장]
                        this.response.put(RESPONSE_DATA, "[EXCEPTION] : [0] : [RequestSyncDeleteHttp] : " + 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 + " >> RequestSyncDeleteHttp :: OK HTTP 동기 DELETE [에러] 확인]")
                    S_Log.cnt("-----------------------------------------")
                    S_Log.cnt("[TYPE :: DELETE >> 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] : [RequestSyncDeleteHttp] : " + responseData) // [메시지 삽입]
                }
            }
            catch (e : Exception) {
                e.printStackTrace()
                S_Log.lte("================================================")
                S_Log.cnt("[" + N_AsyncHttp.ACTIVITY_NAME + " >> RequestSyncDeleteHttp :: OK HTTP 동기 DELETE [Exception] 확인]")
                S_Log.cnt("-----------------------------------------")
                S_Log.cnt("[TYPE :: DELETE >> 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] : [RequestSyncDeleteHttp] : " + e.message.toString()) // [메시지 삽입]
            }
        }


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

    }
 

[결과 출력]

 

W///===========//: ================================================
I/: [N_SyncHttp >> RequestSyncDeleteHttp :: OK HTTP 동기 DELETE [응답] 확인]
I/: -----------------------------------------
I/: [TYPE :: DELETE >> RESPONSE]
I/: -----------------------------------------
I/: [CODE :: 200]
I/: -----------------------------------------
I/: [URL :: https://jsonplaceholder.typicode.com/posts/1]
I/: -----------------------------------------
I/: [HEADER :: date: Fri, 21 Apr 2023 12:10:46 GMT
    content-type: application/json; charset=utf-8
    content-length: 2
    x-powered-by: Express
    x-ratelimit-limit: 1000
    x-ratelimit-remaining: 995
    x-ratelimit-reset: 1682079071
    vary: Origin, Accept-Encoding
    access-control-allow-credentials: true
    cache-control: no-cache
    pragma: no-cache
    expires: -1
    x-content-type-options: nosniff
    etag: W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8"
    via: 1.1 vegur
    cf-cache-status: DYNAMIC
    report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=v%2FAJkWIZV9vNPxjwefn39hKxR9SPPhsRKjRTc8M8hj5T%2B34kQXs3ZJXoGG2MXOg0coawz6DElXue3x9YuAXBmnncD5s6x0SxFB4anzrJzOHQIv8cEq0SjT48hVch%2BsILuupx%2BUOJVm0ACxJZQrGZJ5obnSPhb0zQCJH7"}],"group":"cf-nel","max_age":604800}
    nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
    server: cloudflare
    cf-ray: 7bb586944dd9b451-HKG
    alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400
    ]
I/: -----------------------------------------
I/: [DATA :: {}]
W///===========//: ================================================

 

반응형
Comments