Java
[JAVA] RestTemplate 사용 JSON API 통신
봉주니
2021. 1. 14. 13:14
API를 이용하여 개발을 많이 하다보니 RestTemplate을 자주 사용한다.
JSON 이란?
Java Script Object Notation 의 줄임말로 속성-값 쌍 또는 "키-값 쌍"으로 이루어진 데이터 오브젝트를 전달하기 위해 인간이 읽을 수 있는 텍스트를 사용하는 개방형 표준 포맷이다.
JSON을 쓰기 위해 json-simple jar를 사용합니다.
Maven을 사용하는 경우 pom.xml 에 dependency 설정으로 간단하게 처리됩니다.
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
하지만 저는 gradle 프로젝트를 사용하므로 아래와 같이 사용합니다.
1. 파일 다운로드
2. 일반적으로 web환경 프로젝트일 경우 WEB-INF 파일 아래에 lib 폴더를 생성 후 해당 파일을 넣어주시면 됩니다.
gradle 프로젝트인 경우 아래와 같이 만듭니다.
3. build.gradle 파일에 추가해줍니다.
/*
* This build file was auto generated by running the Gradle 'init' task
* by 'lglis' at '21. 1. 14 오후 12:12' with Gradle 3.0
*
* This generated file contains a sample Java project to get you started.
* For more details take a look at the Java Quickstart chapter in the Gradle
* user guide available at https://docs.gradle.org/3.0/userguide/tutorial_java_projects.html
*/
// Apply the java plugin to add support for Java
apply plugin: 'java'
// In this section you declare where to find the dependencies of your project
repositories {
// Use 'jcenter' for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
// In this section you declare the dependencies for your production and test code
dependencies {
// The production code uses the SLF4J logging API at compile time
compile 'org.slf4j:slf4j-api:1.7.21'
compile files('lib/json-simple-1.1.1.jar')
// Declare the dependency for your favourite test framework you want to use in your tests.
// TestNG is also supported by the Gradle Test task. Just change the
// testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
// 'test.useTestNG()' to your build script.
testCompile 'junit:junit:4.12'
}
서비스 코드는 아래와 같이 사용합니다.
public void jsonTest(Map<String, Object> parameter){
String restRequestUrl = 해당 URL;
RestTemplate restTemplate = new RestTemplate();
JSONObject jsonObject = new JSONObject();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
for( Map.Entry<String, Object> entry : map.entrySet() ) {
String key = entry.getKey();
Object value = entry.getValue();
jsonObject.put(key, value);
}
ResponseEntity<HashMap> response = restTemplate.exchange(restRequestUrl, HttpMethod.POST, new HttpEntity<>(jsonObject.toString(),headers), HashMap.class);
if (response.getStatusCode() != HttpStatus.OK) {
logger.warn("error statusCode = {}, body={}", response.getStatusCode(), response.getBody());
}
}
반응형