성실한 사람이 되자

성실하게 글쓰자

This is spear

JAVA_SPRING/JAVA

OpenAPI 데이터를 자바를 이용해 데이터를 받기(POSTMAN을 이용해 공공데이터 오픈API에 데이터 요청, Java, OkHttp 이용)

Imaspear 2021. 8. 4. 15:20
728x90

 

 

 

공공데이터에서 활용 신청을 받은 후 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해줘야 합니다. 이걸 하지 않으면 의존성 주입이 되지 않고 클래스에서 사용할 수 없습니다. 

Maven 클릭

Reload project를 눌러주세요!

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을 응답받고 데이터들도 정상적으로 송수신되었습니다.