Skip to content

Instantly share code, notes, and snippets.

@an-sangkil
Last active November 17, 2015 00:43
Show Gist options
  • Save an-sangkil/f8542e5934e40529b19f to your computer and use it in GitHub Desktop.
Save an-sangkil/f8542e5934e40529b19f to your computer and use it in GitHub Desktop.
HttpRestTemplateTest
import java.net.SocketTimeoutException;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.conn.ConnectTimeoutException;
import org.springframework.core.NestedRuntimeException;
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.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import cj.cjoext.common.ApplicationRuntimeException;
import cj.cjoext.common.ExtGetBeanUtil;
import cj.cjoext.common.MakeLogFolder;
import cj.cjoext.common.dto.ExtAllthatTokenDto;
import cj.cjoext.service.allthat.common.MessageConverter;
import frameone.core.utility.config.Config;
/**
*
* @author kang
*
*/
public class HttpAllthatConnector {
private Log logger = LogFactory.getLog(HttpAllthatConnector.class);
private static String DEAFULT_URL = ""; //"";
static {
try {
String opMode = Config.getString("operation.mode").toUpperCase(); //어플리케이션 동작 모드 WKR : 로컬실행, DEV : 개발기, STG : 스테이징, PRD : 운영기
if(StringUtils.equals("WKR", opMode) || StringUtils.equals("WKR", opMode)
|| StringUtils.equals("DEV", opMode) || StringUtils.equals("STG", opMode) ) {
//DEAFULT_URL = "http://tst-pjallthatapi.shinhancard.com";
DEAFULT_URL = "http://localhost";
} else {
DEAFULT_URL = "https://allthatadmin.shinhancard.com";
}
} catch(Exception e) {
DEAFULT_URL = "https://allthatadmin.shinhancard.com";
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 파트너ID 정보
*/
private String partnerId;
/**
* token 생성 여부 기본 True
* 헤더로 접근 token [X-ALLTHAT-API-TOKEN]을 생략할 경우 Setter 에 'false'로 선언하여 사용한다.
*/
private boolean tokenYN = true;
public void setTokenYN(boolean tokenYN) {
this.tokenYN = tokenYN;
}
/**
*
* Session Key, Security Key
* @return
* @throws Exception
*/
public HttpHeaders createHeader(MediaType mediaType,List<MediaType> acceptableMediaTypes, boolean tokenYN) throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
// tokenYN GetToken : 처음 토큰을 생성할때는 False 로 셋팅하여 사용한다.
if(tokenYN){
// 접근 토큰 삽입
ExtAllthatTokenDto allThatTokenDto = ExtGetBeanUtil.getItemManAllthatService().getToken(partnerId);
requestHeaders.set("X-ALLTHAT-API-TOKEN", allThatTokenDto.getAccess_token());
}
// 미디어 컨텐트 타입 삽입 기본 TEXT/HTML
if ( mediaType == null || acceptableMediaTypes == null) {
requestHeaders.set("Accept", MediaType.TEXT_HTML_VALUE);
requestHeaders.setContentType(MediaType.TEXT_HTML);
} else {
if(CollectionUtils.isNotEmpty(acceptableMediaTypes)) {
requestHeaders.setAccept(acceptableMediaTypes);
}
requestHeaders.setContentType(mediaType);
}
// requestHeaders.set("Accept", MediaType.APPLICATION_JSON_VALUE);
// requestHeaders.setContentType(MediaType.APPLICATION_JSON);
// requestHeaders.add("Cookie", "X-ALLTHAT-API-SESSION=" + sessionKey);
return requestHeaders;
}
/**
* HTTP.GET Rest 전송 parameter Message
* @param url
* @param clazz
* @param method
* @param uriVariables
* @return
* @throws Exception
*/
public <T> T connecterSendGET (String url , Class<T> clazz, MultiValueMap<String, String> uriVariables) throws ApplicationRuntimeException {
return connecterSend(url, clazz, null, HttpMethod.GET, uriVariables, null);
}
/**
* HTTP.POST Rest 전송 parameter Message
* @param url
* @param clazz
* @param method
* @param uriVariables
* @return
* @throws Exception
*/
public <T> T connecterSendPost (String url , Class<T> clazz, MultiValueMap<String, String> uriVariables) throws ApplicationRuntimeException {
return connecterSend(url, clazz, null, HttpMethod.POST, uriVariables , null);
}
/**
* HTTP.POST RestFull Object 전송
* @param url
* @param clazz
* @param method
* @param t
* @param uriVariables
* @return
* @throws Exception
*/
public <T> T connecterSendPost (String url , Class<T> clazz, HttpMethod method , T t , MultiValueMap<String, String> uriVariables) throws ApplicationRuntimeException {
return connecterSend(url, clazz, t, HttpMethod.POST, uriVariables, null);
}
/**
* 외부 연동
* @param url
* @param clazz
* @param t
* @param method
* @param uriVariables
* @return
* @throws Exception
*
* RestFull 사용시 http://localhost/{param1}/{param2} uriVariables 의 parameter 사용
*
*/
@SuppressWarnings({"unchecked","rawtypes"})
private <T> T connecterSend (String url , Class<T> clazz, T t , HttpMethod method,
MultiValueMap<? extends String, ? extends String> uriVariables,
MediaType mediaType) throws ApplicationRuntimeException {
try {
// 1. MessageConverter 초기화
MessageConverter messageConverter = new MessageConverter();
if(clazz == null ){
throw new ApplicationRuntimeException("잘못된 Response Type 입니다." ,"99" , new Object[]{});
}
// 2. URI 빌드, 쿼리파라미터 삽입, 인코딩(기본 UTF-8)
// GET 의 parameter 셋팅
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(url);;
if(method == HttpMethod.GET) {
if(uriVariables != null) {
Iterator<String> it = (Iterator<String>)uriVariables.keySet().iterator();
while(it.hasNext()){
String keyStr = it.next();
uriComponentsBuilder.queryParam(keyStr, uriVariables.get(keyStr));
}
}
}
url =uriComponentsBuilder.build().encode().toString();
// 3. HTTP 엔티티 설정 (헤더 정보 삽입)
HttpEntity<?> requestEntity = null;
MakeLogFolder makeLogFolder = new MakeLogFolder();
if(t != null) {
String strJSON = MessageConverter.convertObjectToJson(t);
// Post Object Parameter 셋팅
requestEntity = new HttpEntity( strJSON , createHeader(mediaType, null, this.tokenYN));
} else {
requestEntity = new HttpEntity(createHeader(mediaType, null, this.tokenYN));
}
// 4. Template 생성 MessageConvertor
RestTemplate restTemplate = messageConverter.getRestTemplate();
// 5. 외부 API 연결
ResponseEntity<?> responseEntity = restTemplate.exchange(url, method , requestEntity, clazz, uriVariables);
switch(responseEntity.getStatusCode()) {
case OK:
break;
case BAD_REQUEST:
case UNAUTHORIZED:
case NOT_FOUND:
case INTERNAL_SERVER_ERROR:
case SERVICE_UNAVAILABLE:
throw new ApplicationRuntimeException("내부 응답 실패","99",new Object[]{});
default:
throw new ApplicationRuntimeException("내부 응답 알수없는오류","99",new Object[]{});
}
return (T)responseEntity.getBody();
} catch(HttpClientErrorException e) {
logger.error("HttpClientErrorException", e);
throw new ApplicationRuntimeException("외부 연결실패1-4XX","99",new Object[]{});
} catch(HttpServerErrorException e) {
logger.error("HttpServerErrorException", e);
throw new ApplicationRuntimeException("외부 연결실패2-5XX","99",new Object[]{});
} catch (ResourceAccessException e){
if(e.getRootCause() instanceof ConnectTimeoutException) {
logger.error("ConnectTimeoutException", e);
throw new ApplicationRuntimeException("ConnectTimeoutException ","98",new Object[]{});
} else if(e.getRootCause() instanceof SocketTimeoutException) {
logger.error("SocketTimeoutException", e);
throw new ApplicationRuntimeException("SocketTimeoutException ","97",new Object[]{});
} else {
logger.error("ResourceAccessException", e);
throw new ApplicationRuntimeException("외부 연결실패3-IO ","99",new Object[]{});
}
} catch(RestClientException e) {
logger.error("RestClientException", e);
throw new ApplicationRuntimeException("외부 연결실패4","99",new Object[]{});
} catch (NestedRuntimeException e){
logger.error("NestedRuntimeException", e);
throw new ApplicationRuntimeException("외부 연결실패5","99",new Object[]{});
} catch(Exception e) {
logger.error("Exception", e);
throw new ApplicationRuntimeException("알수없는 오류","99",new Object[]{});
}
}
}
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class MessageConverter {
/**
* RestTemplate JSON 자동 컨버터 생성
* @return
*/
public RestTemplate getRestTemplate() {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(30000);
clientHttpRequestFactory.setReadTimeout(30000);
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJacksonHttpMessageConverter map = new MappingJacksonHttpMessageConverter();
XmlAwareFormHttpMessageConverter xml = new XmlAwareFormHttpMessageConverter();
messageConverters.add(map);
messageConverters.add(xml);
restTemplate.setMessageConverters(messageConverters);
return restTemplate;
}
/**
 * JsonString을 Object Class로 전환
 *
 * 사용 Library : Google gson
 *
 * @param jsonString
 * @param objectClass
 * @return
 */
public static <T> T convertJsonToObject(final String jsonString, final Class<T> objectClass) {
Gson gson = new Gson();
return gson.fromJson(jsonString, objectClass);
}
/**
 * Object Class를 Json String으로 전환
 *
 * 사용 Library : Google gson
 *
 * @param jsonString
 * @param objectClass
 * @return
 */
public static String convertObjectToJson(Object objectClass) {
Gson gson = new GsonBuilder().serializeNulls().create();
return gson.toJson(objectClass);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment