투케이2K

533. (Android/Java) [okhttp 4.9.0] [유틸 파일] requestDeleteQueryStringHttp : delete 방식 비동기 http 요청 수행 본문

Android

533. (Android/Java) [okhttp 4.9.0] [유틸 파일] requestDeleteQueryStringHttp : delete 방식 비동기 http 요청 수행

투케이2K 2023. 4. 5. 21:24

[개발 환경 설정]

개발 툴 : AndroidStudio

 

[소스 코드]

    // -----------------------------------------------------------------------------------------
    // TODO [SEARCH FAST] : [DELETE] : [QUERY STRING] : requestDeleteQueryStringHttp
    // -----------------------------------------------------------------------------------------
    // TODO [호출 방법 소스 코드]
    // -----------------------------------------------------------------------------------------
    /*
    try {

        // [URL 주소 선언]
        String url = "https://jsonplaceholder.typicode.com/posts/1";

        // [http 요청 수행]
        N_AsyncHttp.requestDeleteQueryStringHttp(url, null, null) // [http 요청]
                .subscribeOn(AndroidSchedulers.mainThread()) // [Observable (생성자) 로직을 IO 스레드에서 실행 : 백그라운드]
                .observeOn(Schedulers.io()) // [Observer (관찰자) 로직을 메인 스레드에서 실행]
                .subscribe(new Observer<String>() { // [Observable.create 타입 지정]
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull String value) {
                        S_Log.ltw("================================================");
                        S_Log.cnt("["+ACTIVITY_NAME+" >> requestDeleteQueryStringHttp :: onNext]");
                        S_Log.cnt("-----------------------------------------");
                        S_Log.cnt("[VALUE :: "+String.valueOf(value)+"]");
                        S_Log.lbw("================================================");
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        S_Log.lte("================================================");
                        S_Log.cnt("["+ACTIVITY_NAME+" >> requestDeleteQueryStringHttp :: onError]");
                        S_Log.cnt("-----------------------------------------");
                        S_Log.cnt("[ERROR :: "+String.valueOf(e.getMessage())+"]");
                        S_Log.lbe("================================================");
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
    catch (Exception e){
        e.printStackTrace();
    }
    */
    // -----------------------------------------------------------------------------------------
    public static Observable<String> requestDeleteQueryStringHttp(String url, Map header, Map params){

        // [로직 처리 실시]
        return Observable.create(subscriber -> {

            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();
                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+" >> requestDeleteQueryStringHttp :: 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+" >> requestDeleteQueryStringHttp :: 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;
                client.newCall(request.build()).enqueue(new Callback() {

                    // TODO [성공한 경우]
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        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+" >> requestDeleteQueryStringHttp :: 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 [정상 응답]

                                // TODO [결과 전송 실시]
                                subscriber.onNext(responseData);
                                subscriber.onComplete();

                            }
                            else { // TODO [에러 응답]
                                subscriber.onError(new Throwable("[ERROR] : : [requestDeleteQueryStringHttp] : " + C_Msg.getErrorHttpMsg(responseCode)));
                            }
                        }
                        catch (Exception e){
                            e.printStackTrace();
                            subscriber.onError(new Throwable("[EXCEPTION] : [1] : [requestDeleteQueryStringHttp] : " + e.getMessage()));
                        }

                        // ------------------------------------------------------

                    }

                    //TODO [실패한 경우]
                    @Override
                    public void onFailure(Call call, IOException e) {

                        final String responseUrl = String.valueOf(finalUrlData);
                        final String responseError = String.valueOf(e.getMessage());

                        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 :: "+String.valueOf(responseUrl)+"]");
                        S_Log.cnt("-----------------------------------------");
                        S_Log.cnt("[ERROR :: "+String.valueOf(responseError)+"]");
                        S_Log.lbe("================================================");

                        // ------------------------------------------------------
                        // TODO [리턴 데이터 반환]
                        // ------------------------------------------------------
                        try {
                            subscriber.onError(new Throwable("[FAIL] : [requestDeleteQueryStringHttp] : " + responseError));
                        }
                        catch (Exception ex){
                            ex.printStackTrace();
                        }
                    }
                });

            } catch (final Exception e){
                e.printStackTrace();
                S_Log.lte("================================================");
                S_Log.cnt("["+ACTIVITY_NAME+" >> requestDeleteQueryStringHttp :: 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 {
                    subscriber.onError(new Throwable("[EXCEPTION] : [2] : [requestDeleteQueryStringHttp] : " + String.valueOf(e.getMessage())));
                }
                catch (Exception ex){
                    ex.printStackTrace();
                }
            }

        });
    }
 

[결과 출력]

 

W///===========//: ================================================
I/: [A_Intro >> requestDeleteQueryStringHttp :: onNext]
I/: -----------------------------------------
I/: [VALUE :: {}]
W///===========//: ================================================

 

반응형
Comments