Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

J 의 기록

[okhttp3] okhttp3 를 이용한 get/post restclient 본문

개발

[okhttp3] okhttp3 를 이용한 get/post restclient

Luctor 2021. 4. 1. 11:18

회사에서 기존 restutil 을 고도화 할 일이 생겼다.

 

기존 restutil은 post 만 처리 가능하고, header에 대한 고려가 전혀 안되어있기 때문인데

 

일을 하며 java에서 okhttp3를 다뤄 get post 를 쓰는 일은 허다했기 때문에 이번 기회에 정리해보고 제대로 만들어보고자 한다!

 

자 그럼 기존 restutil 부터 살펴보자

 

 

기존 restutil

package ****;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.HashMap;
import java.util.Map;

public class RestUtil {
    public static Map<String, Object> restCall(String url, String path, Map<String, Object> paramMap) throws Exception {
        Map<String, Object> rtnMap = new HashMap<>();
        JsonUtil jsonUtil = new JsonUtil();
        String paramJson = jsonUtil.mapToJson(paramMap);
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder().add("param", paramJson).build();

        Request request = new Request.Builder().url(url + path)
                .post(formBody)
                .build();

        try (Response response = client.newCall(request).execute()){
            rtnMap = jsonUtil.jsonToMap(response.body().string()) ;
        } catch (Exception e) {
            throw e;
        }
        return rtnMap;
    }
}

 

위에 말했듯이 post밖에 호출하지 못하며 header에 대한 고려가 되어있지 않다.

 

그럼 고도화한 restutil을 살펴보자

package ****;

import ****;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RestUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(RestUtil.class);

    //restutil 고도화 (post // get) + header
    public static Map<String, Object> get(String url, String path) throws Exception {
        return get(url, path, null, 0,null);
    }

    public static Map<String, Object> get(String url, String path, Map<String, Object> paramMap) throws Exception {
        return get(url, path, paramMap, 0, null);
    }

    public static Map<String, Object> get(String url, String path, Map<String, Object> paramMap, int timeout) throws Exception {
        return get(url, path, paramMap, timeout, null);
    }

    public static Map<String, Object> get(String url, String path, Map<String, Object> paramMap, int timeout, Map<String, Object> headerMap) throws Exception {
        Map<String, Object> rtnMap = new HashMap<>();
        JsonUtil jsonUtil = new JsonUtil();
        String targetUrl = (url.startsWith("http") ? url : "http://" + url) + path;
        HttpUrl.Builder httpBuilder = HttpUrl.parse(targetUrl).newBuilder();

        OkHttpClient client = null;

        if (paramMap != null) {
            for (Map.Entry<String, Object> param : paramMap.entrySet()) {
                httpBuilder.addQueryParameter(param.getKey(), param.getValue().toString());
            }
        }

        Request.Builder requestBuilder = new Request.Builder();
        if (headerMap != null) {
            for (Map.Entry<String, Object> param : paramMap.entrySet()) {
                requestBuilder.addHeader(param.getKey(), param.getValue().toString());
            }
        }
        Request request = requestBuilder
                .url(httpBuilder.build())
                .build();

        if (timeout > 0) {
            client = new OkHttpClient().newBuilder()
                    .connectTimeout(timeout, TimeUnit.SECONDS)
                    .readTimeout(timeout, TimeUnit.SECONDS)
                    .build();
        } else {
            client = new OkHttpClient();
        }

        LOGGER.debug("REST CALL(GET) - URL:{}, PARAM:{}", targetUrl, paramMap);

        try (Response response = client.newCall(request).execute()){
            if (response.body() != null) {
                String responseStr = response.body().string();
                LOGGER.debug("response:{}", responseStr);
                rtnMap = jsonUtil.jsonToMap(responseStr);
            }
        } catch (Exception e) {
            LOGGER.error("REST 통신 오류", e);
            throw new Exception("REST 통신 오류");
        }

        return rtnMap;
    }

    public static Map<String, Object> post(String url, String path) throws Exception {
        return post(url, path, null, 0, null);
    }

    public static Map<String, Object> post(String url, String path, Map<String, Object> paramMap) throws Exception {
        return post(url, path, paramMap, 0, null);
    }

    public static Map<String, Object> post(String url, String path, Map<String, Object> paramMap, int timeout) throws Exception {
        return post(url, path, paramMap, timeout, null);
    }

    public static Map<String, Object> post(String url, String path, Map<String, Object> paramMap, int timeout, Map<String, Object> headerMap) throws Exception {
        Map<String, Object> rtnMap = new HashMap<>();
        JsonUtil jsonUtil = new JsonUtil();
        String paramJson = jsonUtil.mapToJson(paramMap);
        String targetUrl = (url.startsWith("http") ? url : "http://" + url) + path;
        OkHttpClient client = null;
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramJson);

        Request.Builder requestBuilder = new Request.Builder();
        if (headerMap != null) {
            for (Map.Entry<String, Object> param : paramMap.entrySet()) {
                requestBuilder.addHeader(param.getKey(), param.getValue().toString());
            }
        }
        Request request = requestBuilder
                .url(targetUrl)
                .post(body)
                .build();

        //set timeout
        if (timeout > 0) {
            client = new OkHttpClient().newBuilder()
                    .connectTimeout(timeout, TimeUnit.SECONDS)
                    .readTimeout(timeout, TimeUnit.SECONDS)
                    .build();
        } else {
            client = new OkHttpClient();
        }

        LOGGER.debug("REST CALL(POST) - URL:{}, PARAM:{}", targetUrl, paramJson);

        try (Response response = client.newCall(request).execute()){
            if (response.body() != null) {
                String responseStr = response.body().string();
                LOGGER.debug("response:{}", responseStr);
                rtnMap = jsonUtil.jsonToMap(responseStr);
            }
        } catch (Exception e) {
            LOGGER.error("REST 통신 오류", e);
            throw new Exception("REST 통신 오류");
        }

        return rtnMap;
    }

}

 

오버라이딩을 통해 timeout, headermap, parammap 등이 없을경우도 고려하였다.

 

참고) jsonutil

package *****;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Map;

/**
 *  JsonUtil
 */
public class JsonUtil {

    private Gson gson;

    public JsonUtil(){
        this.gson = new GsonBuilder().disableHtmlEscaping().create();
    }

    /**
     * JSON String을 map으로 변환
     * @param str
     * @return
     */
    public Map<String, Object> jsonToMap(String str){
        Type type = new TypeToken<Map<String, Object>>(){}.getType();
        return gson.fromJson(str, type);
    }

    /**
     * map을 JSON String으로 변환
     * @param map
     * @return
     */
    public String mapToJson(Map<String, Object> map){
        return this.gson.toJson(map);
    }





}