Notice
Recent Posts
Recent Comments
Link
투케이2K
255. (kotlin/코틀린) [okhttp 4.9.0] [유틸 파일] RequestSyncPostBodyJsonHttp : post body json 방식 동기 http 요청 본문
Kotlin
255. (kotlin/코틀린) [okhttp 4.9.0] [유틸 파일] RequestSyncPostBodyJsonHttp : post body json 방식 동기 http 요청
투케이2K 2023. 4. 8. 21:18[개발 환경 설정]
개발 툴 : AndroidStudio
개발 언어 : Kotlin
[소스 코드]
// ----------------------------------------------------------------------------------
// TODO [SEARCH FAST] : [POST] : [BODY JSON] : requestPostBodyJsonHttp
// ----------------------------------------------------------------------------------
/*
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 requestPostBodyJsonHttp = N_SyncHttp().RequestSyncPostBodyJsonHttp(url, header, params)
requestPostBodyJsonHttp.start()
try {
requestPostBodyJsonHttp.join()
}
catch (e : Exception) {
e.printStackTrace()
}
// [http 응답 확인]
var response = requestPostBodyJsonHttp.getResponse()
S_Log.ltw("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> "+C_Util.getNowMethod(1)+" :: [POST BODY JSON] 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 RequestSyncPostBodyJsonHttp : 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 에 파라미터 추가 실시]
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 + " >> RequestSyncPostBodyJsonHttp :: OK HTTP 동기 POST BODY JSON [헤더] 추가]")
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.post(requestBody)
}
else {
request.post(FormBody.Builder().build())
}
request.url(urlData) //TODO [urlData 추가]
// ------------------------------------------------------
// ------------------------------------------------------
// TODO [요청 로그 출력 실시]
S_Log.ltw("================================================")
S_Log.cnt("[" + ACTIVITY_NAME + " >> RequestSyncPostBodyJsonHttp :: OK HTTP 동기 POST BODY JSON [요청] 실시]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[TYPE :: POST 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("[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 + " >> RequestSyncPostBodyJsonHttp :: OK HTTP 동기 POST BODY JSON [응답] 확인]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[TYPE :: POST 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 [응답 값 삽입]
// ------------------------------------------------------
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] : [RequestSyncPostBodyJsonHttp] : " + C_Msg.getErrorHttpMsg(responseCode)) // [메시지 삽입]
}
} catch (e: Exception) {
e.printStackTrace()
// ------------------------------------------------------
// TODO [응답 값 삽입]
// ------------------------------------------------------
this.response.put(RESPONSE_FLAG, false) // [플래그값 저장]
this.response.put(RESPONSE_DATA, "[EXCEPTION] : [1] : [RequestSyncPostBodyJsonHttp] : " + responseData) // [메시지 삽입]
}
}
catch (e : Exception) {
e.printStackTrace()
S_Log.lte("================================================")
S_Log.cnt("[" + N_AsyncHttp.ACTIVITY_NAME + " >> RequestSyncPostBodyJsonHttp :: OK HTTP 동기 POST BODY JSON [Exception] 확인]")
S_Log.cnt("-----------------------------------------")
S_Log.cnt("[TYPE :: POST BODY JSON >> 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] : [RequestSyncPostBodyJsonHttp] : " + e.message.toString()) // [메시지 삽입]
}
}
// [http 요청 성공 및 슬패 결과 값 리턴 함수]
fun getResponse(): Map<String, Any> {
return this.response
}
}
[결과 출력]
W///===========//: ================================================
I/: [N_SyncHttp >> RequestSyncPostBodyJsonHttp :: OK HTTP 동기 POST BODY JSON [요청] 실시]
I/: -----------------------------------------
I/: [TYPE :: POST BODY JSON >> REQUEST]
I/: -----------------------------------------
I/: [URL :: https://jsonplaceholder.typicode.com/posts]
I/: -----------------------------------------
I/: [HEADER :: {}]
I/: -----------------------------------------
I/: [PARAMS :: {id=1, userId=1}]
W///===========//: ================================================
W///===========//: ================================================
I/: [N_SyncHttp >> RequestSyncPostBodyJsonHttp :: OK HTTP 동기 POST BODY JSON [응답] 확인]
I/: -----------------------------------------
I/: [TYPE :: POST BODY JSON >> RESPONSE]
I/: -----------------------------------------
I/: [CODE :: 201]
I/: -----------------------------------------
I/: [URL :: https://jsonplaceholder.typicode.com/posts]
I/: -----------------------------------------
I/: [HEADER :: date: Sat, 08 Apr 2023 12:12:06 GMT
content-type: application/json; charset=utf-8
I/: -----------------------------------------
I/: [DATA :: {
"id": 101,
"userId": 1
}]
W///===========//: ================================================
반응형
'Kotlin' 카테고리의 다른 글
Comments