본문 바로가기
프로그래밍/JAVA

JAVA REST API 호출, oauth2 연동, example code

by 애플 로그 2022. 2. 18.
반응형

JAVA REST API 호출, oauth2 연동, example code

최근에 서버사이드 java코드에서 oauth2를 연동할일이 있었는데, java로 호출샘플 코드를 남겨 놓는다.

sendPost를 함수 통해 RESTAPI를 호출 하거나, oauth2 연동 호출 하는데 사용하면 되겠다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

 

    private static final int timeout = 30 * 1000;

    public static String sendPost(String url, Map parameterMap, String accessToken)
    {
        Map paramMap = parameterMap;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = null;

        try
        {
            HttpPost post = new HttpPost(url);
            RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(timeout)
                .setConnectionRequestTimeout(timeout)
                .setSocketTimeout(timeout)
                .build();

            HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(config);
            httpClient = builder.setSSLSocketFactory(getSSLSocketFactory()).
                disableCookieManagement().build();

            String jsonString = new GsonBuilder().disableHtmlEscaping().create().toJson(parameterMap);
            HttpEntity stringEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
            post.setEntity(stringEntity);

            if ( StringUtil.isNotEmpty(accessToken))
            {
                post.setHeader("Authorization","Bearer " + accessToken);
            }

            // Execute the method.
            httpResponse = httpClient.execute(post);

            result = getResultContent(httpResponse);
            System.out.println("result : " + result);

        }
        catch (IOException e)
        {
            System.out.println("sendPost - IOException ... : " + url);
        }
        catch(Exception e)
        {
            System.out.println("sendPost - Exception ... : " + url);
        }
        finally
        {
            try
            {
                if (httpClient != null) {
                    httpClient.close();
                }

                if (httpResponse != null) {
                    httpResponse.close();
                }
            }
            catch (IOException e)
            {
                System.out.println( e);
            }
        }

        return result;
    }

    private static String getResultContent(CloseableHttpResponse httpResponse) throws IOException
    {
        InputStream in = httpResponse.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null)
        {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }

    private static SSLConnectionSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException
    {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
        SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());

        return connectionFactory;
    }

 

oauth2 방식중 Bearer Authentication 방식으로 access token을 내려 받아야 했다.

oauth 인증 알고 보면 거의 다 거기라 크게 어려울것은 없다.

 

 

1. token 발급

        String url = "https://api.test.com/tokens";
        HashMap map = new HashMap<String,String>();
        map.put("client_id","ynkim");
        map.put("client_secret","password");
        map.put("grant_type","credential");
        
        
        String result = sendPost(url, map,null);
        
        String accessToken = (String) new Gson().fromJson(result, HashMap.class).get("access_token");

 

2. API 실행

sendPost(callUrl.toString(), paramMap, accessToken);

 

발급받은 accessToken을 헤더값에 넣어서 호출하면 된다.

            if ( StringUtil.isNotEmpty(accessToken))
            {
                post.setHeader("Authorization","Bearer " + accessToken);
            }

 

 

댓글