공공데이터에서 활용 신청을 받은 후 POSTMAN, OkHttp, Java를 이용해 데이터를 받아보도록 하겠습니다.
POSTMAN에서 Request 요청을 받을 데이터들을 다 작성한 후 코드 스니펫으로 Java - OkHttp를 선택해 코드를 직접 보면 됩니다.
아래와 같은 코드가 나옵니다.
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"{\n \"businesses\": " +
" [\n " +
" {\n " +
" \"b_no\": \"0000000000\",\n " +
" \"start_dt\": \"20000101\",\n " +
" \"p_nm\": \"홍길동\",\n " +
" \"p_nm2\": \"홍길동\",\n " +
" \"b_nm\": \"(주)테스트\",\n " +
" \"corp_no\": \"0000000000000\",\n " +
" \"b_sector\": \"\",\n " +
" \"b_type\": \"\"\n " +
" }\n " +
" ]\n" +
"}");
Request request = new Request.Builder()
.url("http://api.odcloud.kr/api/nts-businessman/v1/validate?serviceKey={서비스키 입력하세요 !!}")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
OkHttp
그런 다음 OkHttp 의존성 주입을 꼭 해야합니다. 아래에 들어가면 대략적인 설명이 있습니다.
https://square.github.io/okhttp/
OkHttp
OkHttp HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth. OkHttp is an HTTP client that’s efficient by default: HTTP/2 support allows all requests to
square.github.io
아래 접은글을 보면 제 자바 프로젝트 파일의 의존성을 볼 수 있습니다. 현재는 jackson-databind와 okhttp를 의존성 주입했고, property를 이용해 버전을 관리했습니다.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>jackson_type_from_OpenAPI</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<jackson.version>2.12.4</jackson.version>
<okhttp.version>3.10.0</okhttp.version>
</properties>
</project>
간단하게 의존성 주입해도 됩니다.
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
</dependencies>
<properties>
<okhttp.version>3.10.0</okhttp.version>
</properties>
그런다음 꼭 Maven을 Reload해줘야 합니다. 이걸 하지 않으면 의존성 주입이 되지 않고 클래스에서 사용할 수 없습니다.
Reload project를 눌러주세요!
Okhttp에서 기본적으로 데이터를 요청하는 방법을 적어뒀습니다. 참고하세요.
Get URL
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
Post to a server
public static final MediaType JSON
= MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
제 데이터는 서버에서 POST 요청을 해 데이터를 요청했습니다.
throws IOException 를 해주지 않는다면 execute()에서 error가 납니다!!
import okhttp3.*;
import java.io.IOException;
public class test2 {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"{\n \"businesses\": " +
" [\n " +
" {\n " +
" \"b_no\": \"0000000000\",\n " +
" \"start_dt\": \"20000101\",\n " +
" \"p_nm\": \"홍길동\",\n " +
" \"p_nm2\": \"홍길동\",\n " +
" \"b_nm\": \"(주)테스트\",\n " +
" \"corp_no\": \"0000000000000\",\n " +
" \"b_sector\": \"\",\n " +
" \"b_type\": \"\"\n " +
" }\n " +
" ]\n" +
"}");
Request request = new Request.Builder()
.url("http://api.odcloud.kr/api/nts-businessman/v1/validate?serviceKey={서비스키}")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
실행한 모습을 보면 정상적으로 code: 200을 응답받고 데이터들도 정상적으로 송수신되었습니다.
'JAVA_SPRING > JAVA' 카테고리의 다른 글
String 클래스에 대한 학습 테스트 (0) | 2022.02.05 |
---|---|
Set Collection에 대한 학습 테스트 (0) | 2022.02.05 |
자바 기본자료형(Primitive data type)을 왜 사용할까? (0) | 2022.01.29 |
자바 스트림(Java stream) - foreach() 메소드를 이용 (0) | 2020.08.22 |
자바 람다 표현식_자바 버전 8(Lambda expression in Java version 8) (0) | 2020.06.24 |