Notice
Recent Posts
Recent Comments
Link
투케이2K
252. (kotlin/코틀린) [okhttp 4.9.0] [유틸 파일] requestPatchBodyJsonHttp : Patch 방식 비동기 http 요청 수행 본문
Kotlin
252. (kotlin/코틀린) [okhttp 4.9.0] [유틸 파일] requestPatchBodyJsonHttp : Patch 방식 비동기 http 요청 수행
투케이2K 2023. 4. 5. 21:04[개발 환경 설정]
개발 툴 : AndroidStudio
개발 언어 : Kotlin
[소스 코드]
// ----------------------------------------------------------------------------------
// TODO [SEARCH FAST] : [PATCH] : [BODY JSON] : requestPatchBodyJsonHttp
// ----------------------------------------------------------------------------------
// TODO [호출 방법 소스 코드]
// ----------------------------------------------------------------------------------
/*
try {
// [URL 주소 선언]
val url = "https://jsonplaceholder.typicode.com/posts/1"
// [헤더 생성]
val header: MutableMap<String, Any> = HashMap()
// [파라미터 생성]
val params: MutableMap<String, Any> = HashMap()
params["title"] = "foo"
// [http 요청 수행]
N_AsyncHttp.requestPatchBodyJsonHttp(url, header, params)
.subscribeOn(AndroidSchedulers.mainThread()) // [Observable (생성자) 로직을 IO 스레드에서 실행 : 백그라운드]
.observeOn(Schedulers.io()) // [Observer (관찰자) 로직을 메인 스레드에서 실행]
.subscribe(
{ value ->
S_Log.ltw("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> requestPatchBodyJsonHttp :: onNext]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[VALUE :: $value]")
S_Log.lbw("================================================")
},
{ error ->
S_Log.lte("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> requestPatchBodyJsonHttp :: onError]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[ERROR :: " + error.message.toString() + "]")
S_Log.lbe("================================================")
}
)
{
}
}
catch (e : Exception) {
e.printStackTrace()
}
*/
// ----------------------------------------------------------------------------------
fun requestPatchBodyJsonHttp(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 [BODY에 파라미터 추가 실시]
var requestBody: RequestBody? = null
var bodyData = ""
if (C_Util.mapNotNull(params) === true) { // [파라미터가 있는 경우]
// [json 데이터로 변경 실시]
bodyData = C_Util.mapToJsonObject(params).toString()
requestBody = bodyData.toRequestBody("application/json; charset=utf-8".toMediaType())
}
// ------------------------------------------------------
// ------------------------------------------------------
// 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/json") //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 + " >> requestPatchBodyJsonHttp :: OK HTTP 비동기 PATCH QUERY STRING [헤더] 추가]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[KEY :: $key]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[VALUE :: " + header[key].toString() + "]")
S_Log.lbd("================================================")
}
}
if (requestBody != null){
request.put(requestBody)
}
else {
request.put(FormBody.Builder().build())
}
request.url(urlData) //TODO [urlData 추가]
// ------------------------------------------------------
// ------------------------------------------------------
// TODO [요청 로그 출력 실시]
S_Log.ltw("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> requestPatchBodyJsonHttp :: OK HTTP 비동기 PATCH BODY JSON [요청] 실시]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[TYPE :: PATCH BODY JSON >> REQUEST]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[URL :: $urlData]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[HEADER :: $header]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[BODY :: $bodyData]")
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 + " >> requestPatchBodyJsonHttp :: OK HTTP 비동기 PATCH BODY JSON [응답] 확인]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[TYPE :: PATCH BODY JSON >> 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] : : [requestPatchBodyJsonHttp] : " + C_Msg.getErrorHttpMsg(responseCode)))
}
} catch (e: Exception) {
e.printStackTrace()
subscriber.onError(Throwable("[EXCEPTION] : [1] : [requestPatchBodyJsonHttp] : " + e.message.toString()))
}
// ------------------------------------------------------
}
//TODO [실패한 경우]
override fun onFailure(call: Call, e: IOException) {
val responseError = e.message.toString()
S_Log.lte("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> requestPatchBodyJsonHttp :: OK HTTP 비동기 PATCH BODY JSON [에러] 확인]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[TYPE :: PATCH BODY JSON >> 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] : [requestPatchBodyJsonHttp] : $responseError"))
} catch (ex: Exception) {
ex.printStackTrace()
}
}
})
} catch (e: Exception) {
e.printStackTrace()
S_Log.lte("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> requestPatchBodyJsonHttp :: OK HTTP 비동기 PATCH BODY JSON [Exception] 확인]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[TYPE :: PATCH BODY JSON >> EXCEPTION]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[EXCEPTION :: " + e.message.toString() + "]")
S_Log.lbe("================================================")
// ------------------------------------------------------
// TODO [리턴 데이터 반환]
// ------------------------------------------------------
try {
subscriber.onError(Throwable("[EXCEPTION] : [2] : [requestPatchBodyJsonHttp] : " + e.message.toString()))
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}
}
[결과 출력]
W///===========//: ================================================
I/: [A_Intro >> requestPatchBodyJsonHttp :: onNext]
I/: -----------------------------------------
I/: [VALUE :: {
"title": "foo",
"id": 1
}]
W///===========//: ================================================
반응형
'Kotlin' 카테고리의 다른 글
Comments