투케이2K

863. (Android/Java) [GraphQL] Mutation 방식 API 요청 및 응답 확인 수행 본문

Android

863. (Android/Java) [GraphQL] Mutation 방식 API 요청 및 응답 확인 수행

투케이2K 2024. 9. 4. 09:05

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Java / Kotlin

 

[소스 코드]

    // -----------------------------------------------------------------------------------------
    // TODO [SEARCH FAST] : requestMutationHttp
    // -----------------------------------------------------------------------------------------
    // TODO [호출 방법 소스 코드]
    // -----------------------------------------------------------------------------------------
    /*
    try {

        // [URL 주소 선언]
        String url = "https://graphql.postman-echo.com/graphql";

        // [파라미터 생성]
        Map<String, Object> headers = new HashMap<>();
        //headers.put("x-api-key", "sample_key"); // [key 인증시 사용]

        // [GraphQL 요청 형식 선언 : .graphql]
        String graphql = "";
        graphql += "mutation CreatePerson {\n" +
                "    createPerson(person: {name: \"Larry David\", age: 47}) {\n" +
                "        age\n" +
                "        id\n" +
                "        name\n" +
                "    }\n" +
                "}";

        // [http 요청 수행]
        C_GraphQL_Client_Module.requestMutationHttp(A_Intro.this, "GraphQL Http 요청", url, headers, graphql) // [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) {

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
    catch (Exception e){
        S_Log._printStackTrace_(null, S_FinalData.LOG_BUG_STATE, null, e);
    }
    // */
    // -----------------------------------------------------------------------------------------
    // TODO [샘플 로그]
    // -----------------------------------------------------------------------------------------
    /*
    V  ===================================================================
    [LOG :: CLASS PLACE :: com.example.javaproject.C_Module.C_GraphQL_Client_Module.lambda$requestMutationHttp$1(C_GraphQL_Client_Module.java:642)]
    ----------------------------------------------------
    [LOG :: NOW TIME :: 2024-09-04 08:57:09 수요일]
    ----------------------------------------------------
    [LOG :: DESCRIPTION :: requestMutationHttp :: GraphQL Mutation Http [요청] 실시]
    ----------------------------------------------------
    [LOG :: TAG :: GraphQL Http 요청]
    ----------------------------------------------------
    [LOG :: TYPE :: POST BODY JSON >> REQUEST]
    ----------------------------------------------------
    [LOG :: URL :: https://graphql.postman-echo.com/graphql]
    ----------------------------------------------------
    [LOG :: HEADER :: {Cache-Control=no-cache, Content-Type=application/json}]
    ----------------------------------------------------
    [LOG :: PARAMS :: {"query":"mutation CreatePerson {\n    createPerson(person: {name: \"Larry David\", age: 47}) {\n        age\n        id\n        name\n    }\n}"}]
    V  ===================================================================


    V  ===================================================================
    [LOG :: CLASS PLACE :: com.example.javaproject.C_Module.C_GraphQL_Client_Module$4.onResponse(C_GraphQL_Client_Module.java:671)]
    ----------------------------------------------------
    [LOG :: NOW TIME :: 2024-09-04 08:57:11 수요일]
    ----------------------------------------------------
    [LOG :: DESCRIPTION :: requestMutationHttp :: GraphQL Mutation Http [응답] 확인]
    ----------------------------------------------------
    [LOG :: TAG :: GraphQL Http 요청]
    ----------------------------------------------------
    [LOG :: TYPE :: POST BODY JSON >> RESPONSE]
    ----------------------------------------------------
    [LOG :: CODE :: 200]
    ----------------------------------------------------
    [LOG :: URL :: https://graphql.postman-echo.com/graphql]
    ----------------------------------------------------
    [LOG :: HEADER :: date: Tue, 03 Sep 2024 23:57:11 GMT
    ----------------------------------------------------
    [LOG :: DATA :: {"data":{"createPerson":{"age":47,"id":"61","name":"Larry David"}}}]
    V  ===================================================================
    */
    // -----------------------------------------------------------------------------------------
    public static Observable<String> requestMutationHttp(Context mContext, String tag, String url, Map header, String graphql){

        // [로직 처리 실시]

        return Observable.create(subscriber -> {

            try {

                // ------------------------------------------------------
                // TODO [사전 방어 로직 : body 데이터 값 체크 실시]
                // ------------------------------------------------------
                if (C_Util.stringNotNull(graphql) == false || graphql.startsWith("mutation") == false){
                    try { subscriber.onError(new Throwable("[FAIL] : [requestMutationHttp] : Input Query Is Null or startsWith False")); } catch (Exception ex){ ex.printStackTrace(); }
                    return;
                }
                // ------------------------------------------------------



                // ------------------------------------------------------
                // TODO [사전 방어 로직 : url 데이터 값 체크 실시]
                // ------------------------------------------------------
                if (C_Util.stringNotNull(url) == false){
                    try { subscriber.onError(new Throwable("[FAIL] : [requestMutationHttp] : Input Url Is Null")); } catch (Exception ex){ ex.printStackTrace(); }
                    return;
                }
                // ------------------------------------------------------



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



                // ------------------------------------------------------
                // TODO [BODY에 파라미터 추가 실시]
                // ------------------------------------------------------
                RequestBody requestBody = null;
                String bodyData = "";
                if (C_Util.stringNotNull(graphql) == true) { // [파라미터가 있는 경우]

                    // [json 데이터로 변경 실시]
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("query", graphql);

                    bodyData = jsonObject.toString();
                    requestBody = RequestBody.create(bodyData, MediaType.parse("application/json; charset=utf-8"));

                }
                // ------------------------------------------------------



                // ------------------------------------------------------
                // TODO [HTTP 통신 전문 로그 기록]
                // ------------------------------------------------------
                S_FileManager.appHttpLogSave(mContext, "\n\n\n\n\n\n\n\n\n");
                S_FileManager.appHttpLogSave(mContext, "TAG :: " + String.valueOf(tag));
                HttpLoggingInterceptor httpLogger = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {
                        if (mContext != null){
                            S_FileManager.appHttpLogSave(mContext, message);
                        }
                    }
                });
                httpLogger.setLevel(HttpLoggingInterceptor.Level.BODY);
                // ------------------------------------------------------



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

                Request.Builder request = new Request.Builder();
                request.addHeader("Content-Type", "application/json"); //TODO [헤더]
                request.addHeader("Cache-Control", "no-cache"); //TODO [헤더]

                // [로그 출력 헤더 삽입]
                Map<String, String> requestHeader = new HashMap<>();
                requestHeader.put("Content-Type", "application/json");
                requestHeader.put("Cache-Control", "no-cache");

                if (C_Util.mapNotNull(header) == true){
                    Set set = header.keySet();
                    Iterator iterator = set.iterator();
                    while(iterator.hasNext()){
                        String key = (String) iterator.next();
                        requestHeader.put(key, String.valueOf(header.get(key)));
                        request.addHeader(key, String.valueOf(header.get(key))); //TODO [헤더 추가]
                    }

                }

                HttpUrl.Builder httpBuilder = HttpUrl.get(URI.create(urlData)).newBuilder();

                if (requestBody != null){
                    request.post(requestBody);
                }
                else {
                    request.post(new FormBody.Builder().build());
                }

                request.url(httpBuilder.build()); //TODO [httpBuilder 추가]
                // ------------------------------------------------------



                // ------------------------------------------------------
                // TODO [요청 로그 출력 실시]
                // ------------------------------------------------------
                S_Log._F_(mContext, "requestMutationHttp :: GraphQL Mutation Http [요청] 실시", new String[] {
                        "TAG :: " + String.valueOf(tag),
                        "TYPE :: " + "POST BODY JSON >> REQUEST",
                        "URL :: " + String.valueOf(urlData),
                        "HEADER :: " + String.valueOf(requestHeader),
                        "PARAMS :: " + String.valueOf(bodyData)
                });
                // ------------------------------------------------------



                // ------------------------------------------------------
                // 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._F_(mContext, "requestMutationHttp :: GraphQL Mutation Http [응답] 확인", new String[] {
                                "TAG :: " + String.valueOf(tag),
                                "TYPE :: " + "POST BODY JSON >> RESPONSE",
                                "CODE :: " + String.valueOf(responseCode),
                                "URL :: " + String.valueOf(responseUrl),
                                "HEADER :: " + String.valueOf(responseHeader),
                                "DATA :: " + String.valueOf(responseData)
                        });
                        // ------------------------------------------------------


                        // ------------------------------------------------------
                        // 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] : : [requestMutationHttp] : " + C_ErrorCheck.getErrorHttpMsg(responseCode)));
                            }
                        }
                        catch (Exception e){
                            S_Log._printStackTrace_(mContext, S_FinalData.LOG_BUG_STATE, null, e);
                            subscriber.onError(new Throwable("[EXCEPTION] : [1] : [requestMutationHttp] : " + 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._F_(mContext, "requestMutationHttp :: GraphQL Mutation Http [에러] 확인", new String[] {
                                "TAG :: " + String.valueOf(tag),
                                "TYPE :: " + "POST BODY JSON >> FAIL",
                                "URL :: " + String.valueOf(responseUrl),
                                "DATA :: " + String.valueOf(responseError)
                        });
                        // ------------------------------------------------------


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

            } catch (final Exception e){
                // ------------------------------------------------------
                // [로그 출력]
                // ------------------------------------------------------
                S_Log._printStackTrace_(mContext, S_FinalData.LOG_BUG_STATE, new String[] {
                        "requestMutationHttp :: GraphQL Mutation Http [EXCEPTION] 확인",
                        "TAG :: " + String.valueOf(tag),
                        "TYPE :: " + "POST BODY JSON >> EXCEPTION",
                        "EXCEPTION :: " + String.valueOf(e.getMessage())
                }, e);
                // ------------------------------------------------------


                // ------------------------------------------------------
                // TODO [리턴 데이터 반환]
                // ------------------------------------------------------
                try { subscriber.onError(new Throwable("[EXCEPTION] : [2] : [requestMutationHttp] : " + String.valueOf(e.getMessage()))); } catch (Exception ex){ ex.printStackTrace(); }
                // ------------------------------------------------------
            }

        });
    }
 

[결과 출력]

 

반응형
Comments