투케이2K

553. (Android/Java) [유틸 파일] requestDeleteQueryStringHttp : delete 방식 동기식 http 요청 수행 실시 본문

Android

553. (Android/Java) [유틸 파일] requestDeleteQueryStringHttp : delete 방식 동기식 http 요청 수행 실시

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

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Java

 

[소스 코드]

    // -----------------------------------------------------------------------------------------
    // TODO [SEARCH FAST] : [DELETE] : [QUERY STRING] : requestDeleteQueryStringHttp
    // -----------------------------------------------------------------------------------------
    // TODO [호출 방법 소스 코드]
    // -----------------------------------------------------------------------------------------
    /*
    try {
        // TODO [로딩 프로그레스 활성]
        C_Ui_View.startLoadingAlert(
                A_Intro.this,
                S_FinalMsg.AL_TITLE,
                "[HTTP] 요청 중 입니다. 잠시만 기다려 주세요.",
                S_FinalMsg.AL_OK);


        // TODO [새로운 스레드 생성 및 동기 요청 실시]
        new Thread(){
            @Override
            public void run(){
                try {

                    // TODO [순차적 요청 수행]
                    for (int i=0; i<10; i++){

                        // TODO [URL 및 데이터 생성]
                        String url = "https://jsonplaceholder.typicode.com/posts/1";

                        Map header = new HashMap();

                        Map params = new HashMap();


                        // TODO [http 통신 시작]
                        N_SyncHttp.RequestSyncDeleteHttp requestSyncDeleteHttp = new N_SyncHttp.RequestSyncDeleteHttp(url, header, params);
                        requestSyncDeleteHttp.start();
                        try{
                            requestSyncDeleteHttp.join(); // [스레드 작업 완료까지 대기]
                        }catch(Exception e){
                            e.printStackTrace();
                        }


                        // TODO [http 통신 응답 값 확인]
                        Map response = requestSyncDeleteHttp.getResponse();
                        S_Log.ltw("================================================");
                        S_Log.cnt("["+ACTIVITY_NAME+" >> "+C_Util.getNowMethod(1)+" :: [DELETE] HTTP 통신 수행 결과]");
                        S_Log.cnt("[SUCCESS :: "+response.get(N_SyncHttp.RESPONSE_FLAG)+"]");
                        S_Log.cnt("[DATA :: "+response.get(N_SyncHttp.RESPONSE_DATA)+"]");
                        S_Log.lbw("================================================");

                    }


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

                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }
    catch (Exception e){
        e.printStackTrace();
    }
    */
    // -----------------------------------------------------------------------------------------
    public static class RequestSyncDeleteHttp extends Thread {

        // [변수 선언 실시]
        String url = "";
        Map header = new HashMap();
        Map params = new HashMap();


        // [http 요청 후 응답 값 리턴]
        private Map response = new HashMap(); // [http 요청 성공 및 실패 플래그값]


        // [클래스 생성자 초기화]
        public RequestSyncDeleteHttp(String url, Map header, Map params){
            this.url = url;
            this.header = header;
            this.params = params;
        }


        // [http 수행 실시]
        public void run() {
            try {

                // ------------------------------------------------------
                // TODO [URL 변수 선언 실시]
                String urlData = String.valueOf(url);
                // ------------------------------------------------------


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

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

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


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

                Request.Builder request = new 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){
                    Set set = header.keySet();
                    Iterator iterator = set.iterator();
                    while(iterator.hasNext()){
                        String key = (String) iterator.next();
                        request.addHeader(key, String.valueOf(header.get(key))); //TODO [헤더 추가]

                        S_Log.ltd("================================================");
                        S_Log.cnt("["+ACTIVITY_NAME+" >> RequestSyncDeleteHttp :: OK HTTP 동기 DELETE [헤더] 추가]");
                        S_Log.cnt("-----------------------------------------");
                        S_Log.cnt("[KEY :: "+String.valueOf(key)+"]");
                        S_Log.cnt("-----------------------------------------");
                        S_Log.cnt("[VALUE :: "+String.valueOf(header.get(key))+"]");
                        S_Log.lbd("================================================");
                    }
                }

                HttpUrl.Builder httpBuilder = HttpUrl.get(URI.create(urlData)).newBuilder();
                request.url(httpBuilder.build()).delete().build(); //TODO [httpBuilder 추가]
                // ------------------------------------------------------


                // ------------------------------------------------------
                // 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 :: "+String.valueOf(urlData)+"]");
                S_Log.cnt("-----------------------------------------");
                S_Log.cnt("[HEADER :: "+String.valueOf(header)+"]");
                S_Log.cnt("-----------------------------------------");
                S_Log.cnt("[PARAMS :: "+String.valueOf(params)+"]");
                S_Log.lbw("================================================");
                // ------------------------------------------------------


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

                //TODO [동기 처리 (execute 사용)]
                Response response = client.newCall(request.build()).execute();
                if (response.isSuccessful()) { //TODO [요청이 성공한 경우]

                    final String responseUrl = String.valueOf(finalUrlData);
                    final String responseHeader = String.valueOf(response.headers().toString());
                    final String responseCode = String.valueOf(response.code());
                    final String responseData = String.valueOf(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 :: "+String.valueOf(responseCode)+"]");
                    S_Log.cnt("-----------------------------------------");
                    S_Log.cnt("[URL :: "+String.valueOf(responseUrl)+"]");
                    S_Log.cnt("-----------------------------------------");
                    S_Log.cnt("[HEADER :: "+String.valueOf(responseHeader)+"]");
                    S_Log.cnt("-----------------------------------------");
                    S_Log.cnt("[DATA :: "+String.valueOf(responseData)+"]");
                    S_Log.lbw("================================================");

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

                            // [응답 값 삽입]
                            this.response.put(RESPONSE_FLAG, true); // [플래그값 저장]
                            this.response.put(RESPONSE_DATA, responseData); // [메시지 삽입]

                        }
                        else { // TODO [에러 응답]

                            // [응답 값 삽입]
                            this.response.put(RESPONSE_FLAG, false); // [플래그값 저장]
                            this.response.put(RESPONSE_DATA, "[ERROR] : [RequestSyncDeleteHttp] : " + String.valueOf(C_Msg.getErrorHttpMsg(responseCode))); // [메시지 삽입]

                        }
                    }
                    catch (Exception e){
                        e.printStackTrace();

                        // [응답 값 삽입]
                        this.response.put(RESPONSE_FLAG, false); // [플래그값 저장]
                        this.response.put(RESPONSE_DATA, "[EXCEPTION] : [0] : [RequestSyncDeleteHttp] : " + String.valueOf(e.getMessage())); // [메시지 삽입]
                    }

                }
                else { //TODO [요청이 실패한 경우]
                    final String responseUrl = String.valueOf(finalUrlData);
                    final String responseHeader = String.valueOf(response.headers().toString());
                    final String responseCode = String.valueOf(response.code());
                    final String responseData = String.valueOf(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("[URL :: "+String.valueOf(responseUrl)+"]");
                    S_Log.cnt("-----------------------------------------");
                    S_Log.cnt("[ERROR :: "+String.valueOf(responseData)+"]");
                    S_Log.lbe("================================================");

                    // [응답 값 삽입]
                    this.response.put(RESPONSE_FLAG, false); // [플래그값 저장]
                    this.response.put(RESPONSE_DATA, "[FAIL] : [RequestSyncDeleteHttp] : " + String.valueOf(responseData)); // [메시지 삽입]
                }
            }
            catch (final Exception e){
                S_Log.lte("================================================");
                S_Log.cnt("["+ACTIVITY_NAME+" >> RequestSyncDeleteHttp :: OK HTTP 동기 DELETE [Exception] 확인]");
                S_Log.cnt("-----------------------------------------");
                S_Log.cnt("[TYPE :: DELETE >> EXCEPTION]");
                S_Log.cnt("-----------------------------------------");
                S_Log.cnt("[EXCEPTION :: "+String.valueOf(e.getMessage())+"]");
                S_Log.lbe("================================================");

                // ------------------------------------------------------
                // TODO [리턴 데이터 반환]
                // ------------------------------------------------------
                try {
                    // [응답 값 삽입]
                    this.response.put(RESPONSE_FLAG, false); // [플래그값 저장]
                    this.response.put(RESPONSE_DATA, "[EXCEPTION] : [1] : [RequestSyncDeleteHttp] : " + String.valueOf(e.getMessage())); // [메시지 삽입]
                }
                catch (Exception ex){
                    ex.printStackTrace();

                    // [응답 값 삽입]
                    this.response.put(RESPONSE_FLAG, false); // [플래그값 저장]
                    this.response.put(RESPONSE_DATA, "[EXCEPTION] : [2] : [RequestSyncDeleteHttp] : " + String.valueOf(ex.getMessage())); // [메시지 삽입]
                }
            }
        }

        //TODO [http 요청 성공 및 실패 결과값 리턴해주는 함수]
        public Map getResponse(){
            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:01:28 GMT
    content-type: application/json; charset=utf-8
    content-length: 2
    x-powered-by: Express
    x-ratelimit-limit: 1000
    x-ratelimit-remaining: 990
    x-ratelimit-reset: 1682078531
    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=h7p4q2mN%2FvIvCSq9aScRj2jYzTNZ%2B%2FZrtyS9JHNz6cqQaG2%2Fa3obYley11jJmtTzlfwl0jgU%2FP2s3L%2FZEFiYSwKxAmc1wb27XudybKhDpgthe8WC3y4w1aTqSN712bV%2FZkdq2U0bcGAOx4lP6jzLa%2Fk3ELHdUREX8VVz"}],"group":"cf-nel","max_age":604800}
    nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
    server: cloudflare
    cf-ray: 7bb578f70ec420e9-HKG
    alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400
    ]
I/: -----------------------------------------
I/: [DATA :: {}]
W///===========//: ================================================

 

반응형
Comments