Notice
Recent Posts
Recent Comments
Link
투케이2K
253. (kotlin/코틀린) [okhttp 4.9.0] [유틸 파일] requestDeleteQueryStringHttp : delete 방식 비동기 http 요청 수행 본문
Kotlin
253. (kotlin/코틀린) [okhttp 4.9.0] [유틸 파일] requestDeleteQueryStringHttp : delete 방식 비동기 http 요청 수행
투케이2K 2023. 4. 5. 21:28[개발 환경 설정]
개발 툴 : AndroidStudio
개발 언어 : Kotlin
[소스 코드]
// ----------------------------------------------------------------------------------
// TODO [SEARCH FAST] : [DELETE] : [QUERY STRING] : requestDeleteQueryStringHttp
// ----------------------------------------------------------------------------------
// TODO [호출 방법 소스 코드]
// ----------------------------------------------------------------------------------
/*
try {
// [URL 주소 선언]
val url = "https://jsonplaceholder.typicode.com/posts/1"
// [헤더 생성]
val header: MutableMap<String, Any> = HashMap()
// [파라미터 생성]
val params: MutableMap<String, Any> = HashMap()
// [http 요청 수행]
N_AsyncHttp.requestDeleteQueryStringHttp(url, header, params)
.subscribeOn(AndroidSchedulers.mainThread()) // [Observable (생성자) 로직을 IO 스레드에서 실행 : 백그라운드]
.observeOn(Schedulers.io()) // [Observer (관찰자) 로직을 메인 스레드에서 실행]
.subscribe(
{ value ->
S_Log.ltw("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> requestDeleteQueryStringHttp :: onNext]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[VALUE :: $value]")
S_Log.lbw("================================================")
},
{ error ->
S_Log.lte("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> requestDeleteQueryStringHttp :: onError]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[ERROR :: " + error.message.toString() + "]")
S_Log.lbe("================================================")
}
)
{
}
}
catch (e : Exception) {
e.printStackTrace()
}
*/
// ----------------------------------------------------------------------------------
fun requestDeleteQueryStringHttp(url: String, header: Map<String, Any>, params: Map<String, Any>): Observable<String> {
// [로직 처리 실시]
return Observable.create { subscriber: ObservableEmitter<String> ->
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 + " >> requestDeleteQueryStringHttp :: 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 + " >> requestDeleteQueryStringHttp :: 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
client.newCall(request.build()).enqueue(object : Callback {
//TODO [성공한 경우]
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val responseHeader = response.headers.toString()
val responseCode = response.code.toString()
val responseData = response.body!!.string()
S_Log.ltw("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> requestDeleteQueryStringHttp :: 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 [결과 전송 실시]
subscriber.onNext(responseData)
subscriber.onComplete()
}
else { // TODO [에러 응답]
subscriber.onError(Throwable("[ERROR] : : [requestDeleteQueryStringHttp] : " + C_Msg.getErrorHttpMsg(responseCode)))
}
} catch (e: Exception) {
e.printStackTrace()
subscriber.onError(Throwable("[EXCEPTION] : [1] : [requestDeleteQueryStringHttp] : " + e.message.toString()))
}
// ------------------------------------------------------
}
//TODO [실패한 경우]
override fun onFailure(call: Call, e: IOException) {
val responseError = e.message.toString()
S_Log.lte("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> requestDeleteQueryStringHttp :: OK HTTP 비동기 DELETE [에러] 확인]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[TYPE :: DELETE >> FAIL]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[URL :: $finalUrlData]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[ERROR :: $responseError]")
S_Log.lbe("================================================")
// ------------------------------------------------------
// TODO [리턴 데이터 반환]
// ------------------------------------------------------
try {
subscriber.onError(Throwable("[FAIL] : [requestDeleteQueryStringHttp] : $responseError"))
} catch (ex: Exception) {
ex.printStackTrace()
}
}
})
} catch (e: Exception) {
e.printStackTrace()
S_Log.lte("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> requestDeleteQueryStringHttp :: 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 [리턴 데이터 반환]
// ------------------------------------------------------
try {
subscriber.onError(Throwable("[EXCEPTION] : [2] : [requestDeleteQueryStringHttp] : " + e.message.toString()))
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}
}
[결과 출력]
W///===========//: ================================================
I/: [A_Intro >> requestDeleteQueryStringHttp :: onNext]
I/: -----------------------------------------
I/: [VALUE :: {}]
W///===========//: ================================================
반응형
'Kotlin' 카테고리의 다른 글
Comments