헤르메스 LIFE

[Spring Boot] Spring Resttemplate Sample 본문

Spring Boot Framework

[Spring Boot] Spring Resttemplate Sample

헤르메스의날개 2021. 1. 31. 16:02
728x90

 

개발환경

Spring Boot 2.2.4

JDK 1.8.0_202

REST

Postman : REST Client

 

목표

1. Spring Boot REST 환경

2. JWT + Spring Security 를 통한 인증

3. Resttemplate 조회, 저장


조회

package rest.boot.test;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import rest.boot.model.User;

public class SearchWithRest {
    
    private static Logger logger           = LoggerFactory.getLogger( SearchWithRest.class );
    
    private static String LOCAL_TOKEN_URL  = "http://localhost:8089/v1/signin";
    private static String LOCAL_SEARCH_URL = "http://localhost:8089/api/selectList";
    
    public static void main( String ... args ) throws Exception {
        RestTemplate                  restTemplate = new RestTemplate();
        
        /*
         * X-AUTH-TOKEN 받아오기
         */
        MultiValueMap<String, String> parameters   = new LinkedMultiValueMap<>();
        parameters.add( "id", "admin" );
        parameters.add( "password", "password" );
        
        ResponseEntity<Map> resp = restTemplate.postForEntity( LOCAL_TOKEN_URL, parameters, Map.class );
        logger.debug( "result :: {}", resp.getStatusCodeValue() );
        logger.debug( "result :: {}", resp.getBody() );
        
        if ( resp.getStatusCodeValue() == 200 ) {
            String      xAuthToken = (String) resp.getBody().get( "data" );
            User        user       = new User( "admin", "password" );
            
            HttpHeaders headers    = new HttpHeaders();
            headers.setContentType( MediaType.APPLICATION_JSON );
            headers.add( "X-AUTH-TOKEN", xAuthToken );
            HttpEntity<?>       entity   = new HttpEntity<>( user, headers );
            
            ResponseEntity<Map> response = restTemplate.exchange( LOCAL_SEARCH_URL, HttpMethod.POST, entity, Map.class );
            logger.debug( "result :: {}", response.getStatusCodeValue() );
            logger.debug( "result :: {}", response.getBody() );
            logger.debug( "result :: {}", (List) response.getBody().get( "list" ) );
        }
        
    }
    
}

저장

package rest.boot.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;

import rest.boot.model.User;

public class SaveWithRest {
    
    private static Logger logger          = LoggerFactory.getLogger( SaveWithRest.class );
    
    private static String LOCAL_TOKEN_URL = "http://localhost:8089/v1/signin";
    private static String LOCAL_SAVE_URL  = "http://localhost:8089/api/saveList";
    
    public static void main( String ... args ) throws Exception {
        RestTemplate                  restTemplate = new RestTemplate();
        
        /*
         * X-AUTH-TOKEN 받아오기
         */
        MultiValueMap<String, String> parameters   = new LinkedMultiValueMap<>();
        parameters.add( "id", "admin" );
        parameters.add( "password", "password" );
        
        ResponseEntity<Map> resp = restTemplate.postForEntity( LOCAL_TOKEN_URL, parameters, Map.class );
        logger.debug( "result :: {}", resp.getStatusCodeValue() );
        logger.debug( "result :: {}", resp.getBody() );
        
        List<Object> list = new ArrayList<>();
        list.add( new User( "1", "한글", "aa", "1", "D" ) );
        list.add( new User( "2", "bb", "bb", "2", "D" ) );
        list.add( new User( "3", "cc", "cc", "3", "D" ) );
        list.add( new User( "4", "aa", "aa", "1", "I" ) );
        list.add( new User( "5", "한글", "bb", "2", "I" ) );
        list.add( new User( "6", "cc", "cc", "3", "I" ) );
        list.add( new User( "5", "한글", "bb", "0", "U" ) );
        
        if ( resp.getStatusCodeValue() == 200 ) {
            
            //String sendValue = convert( list );
            //logger.debug( "s={}", sendValue );
            
            /*
             * 데이터 저장
             */
            String      xAuthToken = (String) resp.getBody().get( "data" );
            HttpHeaders headers    = new HttpHeaders();
            headers.setContentType( MediaType.APPLICATION_JSON );
            //headers.setAccept( Collections.singletonList( MediaType.APPLICATION_JSON ) );
            headers.add( "X-AUTH-TOKEN", xAuthToken );
            HttpEntity<?> entity = new HttpEntity<>( list, headers );
            
            logger.debug( "entity :: {}", entity );
            try {
                ResponseEntity<String> response = restTemplate.postForEntity( LOCAL_SAVE_URL, entity, String.class );
                
                logger.debug( "response :: {}", response );
                logger.debug( "result :: {}", response.getStatusCodeValue() );
                logger.debug( "result :: {}", response.getBody() );
                //logger.debug( "result :: {}", (List) response.getBody().get( "list" ) );
            } catch ( HttpStatusCodeException e ) {
                String errorpayload = e.getResponseBodyAsString();
                logger.debug( "error :: {}", errorpayload );
            }
        }
        
    }
    
    public static String convert( Object dto ) {
        ObjectMapper objectMapper = new ObjectMapper();
        
        String       body         = null;
        try {
            body = objectMapper.writeValueAsString( dto );
        } catch ( IOException e ) {
            throw new RuntimeException( e );
        }
        
        return body;
    }
    
}

Spring Resttemplate 예외처리

 

728x90