CLOVA OCR Template API

Version

문서 버전 변경일자 변경사항
v1.0.0 2019-12-05 최초 작성
v1.0.1 2020-02-21 General OCR 응답 바디에 boundingPoly 정보 제공
v2.0.0 2020-03-26 CLOVA OCR 프리미엄 모델 제공으로 멀티박스, 체크박스 인식 기능 추가
요청 버전에 따라 (V1/V2) 결과값에 bounding 및 boundingPoly 정보 제공
※ V2 사용 시 boundingPoly 표시 (권장)
v2.0.1 2021-01-21 General OCR JSON 줄바꿈 정보 제공
ImageField 객체 내 subFiled 삭제
v2.0.1 2021-02-04 convertedImageInfo 필드 추가
v2.0.2 2024-09-26 콘텐츠 항목 정리 및 문구 개선

개요

본 문서에서는 Template OCR의 요청 및 응답 바디에 대해 설명하고 API 구현 예제를 제공합니다.

참고

Post URL과 헤더, 에러코드에 대한 정보는 CLOVA OCR 개요 문서를 참조해 주십시오.

Template OCR

요청 예시

{
  "version": "V2",
  "requestId": "string",
  "timestamp": 0,
  "lang":"ko",
  "images": [
    {
      "format": "jpg",
      "name": "test 1",
      "url": "https://www.ncloud.com/ocr-test/test.jpg",
      "templateIds":[390]
    }
  ]
}

요청 바디

Content-Type : application/json

  • JSON 요청 바디 필드
필드명 필수 여부 타입 설명 제약 사항
version Y string V2: V2 엔진 호출 (권장)
V1: V1 엔진 호출
requestId Y string 임의의 UUID 값 입력
timestamp Y int 임의의 timestamp 값을 숫자로 입력
lang N string OCR 인식을 요청할 언어 정보
ko: 한국어
ja: 일본어
zh-TW: 중국어(번체)
설정되지 않은 경우 도메인의 언어 설정이 기본값으로 지정됨
콤마를 사용하여 다국어 호출 가능 (예 : "ko,ja,zh-TW")
images Y array JSON array로 작성하며, 호출당 1개의 이미지 array만 작성 가능 General OCR은 50MB, Template OCR은 20MB (pdf, tiff는 50MB)까지 지원
images.format Y string jpg, jpeg, png, pdf, tiff 중 택일하여 이미지 포맷을 입력 General OCR은 pdf에 대해 최대 10페이지, Template OCR은 pdf, tiff에 대해 최대 5페이지까지 인식 가능
※ pdf/tiff는 1페이지당 1회 호출 요금이 부과됨
images.url N string 이미지 URL 입력 images.url 혹은 images.data 중 하나를 반드시 설정해야 함
이미지를 불러올 수 있는 공개된 URL이어야 함
images.data N string BASE64 인코딩 된 이미지 데이터 입력 images.url 혹은 images.data 중 하나를 반드시 설정해야 하며
images.url과 images.data를 모두 설정할 경우 images.data가 우선
images.name Y string 임의의 이미지명 입력 이미지를 식별하는 데 사용되며 응답 결과 검증에 사용 가능
images.templateIds N JSON array NCP 콘솔에서 생성한 도메인 내의 템플릿 ID 입력 Template OCR에서만 제공하는 기능
값을 설정하지 않으면 호출한 도메인의 모든 서비스 템플릿으로 자동 분류됨

Content-Type : multipart/form-data

  • CURL example:
curl --request POST 'your apigw invoke url' \
--header 'X-OCR-SECRET: your secret key' \
--data-raw '{"images":[{"format":"jpg","name":"demo","url":"your image url"}],"requestId":"guide-json-demo","version":"V2","timestamp":1584062336793}'
  • Form-data 요청 바디 필드
필드명 필수 여부 타입 설명 제약 사항
version Y string V2: V2 엔진 호출 (권장)
V1: V1 엔진 호출
requestId Y string 임의의 UUID 값 입력
timestamp Y integer 임의의 timestamp 값을 숫자로 입력
lang N string OCR 인식을 요청할 언어 정보
ko: 한국어
ja: 일본어
zh-TW: 중국어(번체)
설정되지 않은 경우 도메인의 언어 설정이 기본값으로 지정됨
콤마를 사용하여 다국어 호가능 (예 : "ko,ja,zh-TW")
images Y string JSON array로 작성하며 호출당 1개의 이미지 array만 작성 가능 General OCR은 50MB, Template OCR은 20MB (pdf, tiff는 50MB)까지 지원
images.format Y string jpg, jpeg, png, pdf, tiff 중 택일하여 이미지 포맷을 입력 General OCR은 pdf에 대해 최대 10페이지, Template OCR은 pdf, tiff에 대해 최대 5페이지까지 인식 가능
※ pdf/tiff는 1페이지당 1회 호출 요금이 부과됨
images.name Y string 임의의 이미지명 입력 이미지를 식별하는 데 사용되며 응답 결과 검증에 사용 가능
images.templateIds N JSON array NCP 콘솔에서 생성한 도메인 내의 템플릿 ID 입력 Template OCR에서만 제공하는 기능< 값을 설정하지 않으면 호출한 도메인의 모든 서비스 템플릿으로 자동 분류됨

응답 예시

{
    "version": "V2",
    "requestId": "string",
    "timestamp": 1584067653255,
    "images": [
        {
            "uid": "1b220cd049de4a7c9e0dc1942d982867",
            "name": "test 1",
            "inferResult": "SUCCESS",
            "message": "SUCCESS",
            "matchedTemplate": {
                "id": 390,
                "name": "template"
            },
            "validationResult": {
                "result": "NO_REQUESTED"
            },
            "title": {
                "name": "title",
                "boundingPoly": {
                    "vertices": [
                        {
                            "x": 453.7125,
                            "y": 54.1125
                        },
                        {
                            "x": 961.5375,
                            "y": 54.1125
                        },
                        {
                            "x": 961.5375,
                            "y": 108.225
                        },
                        {
                            "x": 453.7125,
                            "y": 108.225
                        }
                    ]
                },
                "inferText": "보험금 청구서 (인보험月)",
                "inferConfidence": 0.94674826
            },
            "fields": [
                {
                    "name": "id",
                    "valueType": "NUMERIC",
                    "boundingPoly": {
                        "vertices": [
                            {
                                "x": 488.88235,
                                "y": 284.92896
                            },
                            {
                                "x": 550.3732,
                                "y": 284.93716
                            },
                            {
                                "x": 550.39166,
                                "y": 333.93698
                            },
                            {
                                "x": 488.90073,
                                "y": 333.9292
                            }
                        ]
                    },
                    "inferText": "102831",
                    "inferConfidence": 0.9319761,
                    "type": "MULTI_BOX",
                    "subFields": [
                        {
                            "boundingPoly": {
                                "vertices": [
                                    {
                                        "x": 488.88235,
                                        "y": 284.92896
                                    },
                                    {
                                        "x": 550.3732,
                                        "y": 284.93716
                                    },
                                    {
                                        "x": 550.39166,
                                        "y": 333.93698
                                    },
                                    {
                                        "x": 488.90073,
                                        "y": 333.9292
                                    }
                                ]
                            },
                            "inferText": "1",
                            "inferConfidence": 0.9798796
                        },
                        {
                            "boundingPoly": {
                                "vertices": [
                                    {
                                        "x": 551.37305,
                                        "y": 284.9373
                                    },
                                    {
                                        "x": 612.86285,
                                        "y": 284.9455
                                    },
                                    {
                                        "x": 612.88153,
                                        "y": 333.94495
                                    },
                                    {
                                        "x": 551.39154,
                                        "y": 333.9371
                                    }
                                ]
                            },
                            "inferText": "0",
                            "inferConfidence": 0.6391636
                        },
                        {
                            "boundingPoly": {
                                "vertices": [
                                    {
                                        "x": 613.86273,
                                        "y": 284.94562
                                    },
                                    {
                                        "x": 675.3515,
                                        "y": 284.95383
                                    },
                                    {
                                        "x": 675.3702,
                                        "y": 333.95288
                                    },
                                    {
                                        "x": 613.8812,
                                        "y": 333.94504
                                    }
                                ]
                            },
                            "inferText": "2",
                            "inferConfidence": 0.99591047
                        },
                        {
                            "boundingPoly": {
                                "vertices": [
                                    {
                                        "x": 676.3513,
                                        "y": 284.95395
                                    },
                                    {
                                        "x": 737.8392,
                                        "y": 284.9622
                                    },
                                    {
                                        "x": 737.8579,
                                        "y": 333.96082
                                    },
                                    {
                                        "x": 676.37006,
                                        "y": 333.953
                                    }
                                ]
                            },
                            "inferText": "8",
                            "inferConfidence": 0.99782735
                        },
                        {
                            "boundingPoly": {
                                "vertices": [
                                    {
                                        "x": 738.83887,
                                        "y": 284.96228
                                    },
                                    {
                                        "x": 800.3257,
                                        "y": 284.97052
                                    },
                                    {
                                        "x": 800.34454,
                                        "y": 333.96872
                                    },
                                    {
                                        "x": 738.8577,
                                        "y": 333.9609
                                    }
                                ]
                            },
                            "inferText": "3",
                            "inferConfidence": 0.99916536
                        },
                        {
                            "boundingPoly": {
                                "vertices": [
                                    {
                                        "x": 801.3255,
                                        "y": 284.97064
                                    },
                                    {
                                        "x": 862.8112,
                                        "y": 284.97882
                                    },
                                    {
                                        "x": 862.8301,
                                        "y": 333.97662
                                    },
                                    {
                                        "x": 801.3443,
                                        "y": 333.96884
                                    }
                                ]
                            },
                            "inferText": "1",
                            "inferConfidence": 0.9799099
                        }
                    ]
                },
                {
                    "name": "name",
                    "valueType": "ALL",
                    "boundingPoly": {
                        "vertices": [
                            {
                                "x": 287.2125,
                                "y": 287.2125
                            },
                            {
                                "x": 380.86874,
                                "y": 287.2125
                            },
                            {
                                "x": 380.86874,
                                "y": 328.8375
                            },
                            {
                                "x": 287.2125,
                                "y": 328.8375
                            }
                        ]
                    },
                    "inferText": "David",
                    "inferConfidence": 0.99630755,
                    "type": "NORMAL"
                },
                {
                    "name": "fax-checkbox",
                    "valueType": "ALL",
                    "boundingPoly": {
                        "vertices": [
                            {
                                "x": 87.08151,
                                "y": 736.90735
                            },
                            {
                                "x": 140.0801,
                                "y": 736.91125
                            },
                            {
                                "x": 140.10016,
                                "y": 791.9156
                            },
                            {
                                "x": 87.101494,
                                "y": 791.9121
                            }
                        ]
                    },
                    "inferText": "",
                    "inferConfidence": 0.99464625,
                    "type": "CHECKBOX",
                    "checked": true
                }
            ]
        }
    ]
}

응답 바디 (V2)

Template OCR 요청 바디의 version을 V2로 설정했을 때의 응답 바디를 설명합니다.

1. 응답 바디 필드

필드명 유형 설명
uid string API의 유효성을 검사하기 위해 제공되는 고유 ID로, 유효성 검사 요청을 추적하는 데 사용
name string 요청 바디의 images.name에 입력한 이미지명
inferResult string 이미지 인식 결과
SUCCESS: 이미지 인식 성공
FAILURE: 이미지 인식 실패
ERROR: 이미지 인식 처리예외
message string 이미지 인식 결과에 대한 세부사항
성공 시 SUCCESS 표시
이미지 인식 실패 시 오류 메시지 표시
matchedTemplate JSON object 이미지 인식에 일치한 템플릿 정보로 템플릿 ID와 이름 포함
인식에 실패하거나 일치하는 템플릿을 찾을 수 없는 경우 해당 필드는 표시되지 않음
matchedTemplate.id integer 템플릿 ID
matchedTemplate.name string 템플릿 이름
title string 이미지 타이틀
fields JSON array object ImageField 객체 참조
validationResult JSON object 유효성 검사 결과
validationResult.result string 유효성 검사 결과 코드
NO_REQUESTED: 검증 작업을 요청하지 않음
UNCHECKED: 동작 응답이 확인되지 않거나 응답 미수락
ERROR: 검증 실행에 오류 발생
VALID: 검증 결과가 유효함
INVALID: 검증 결과가 유효하지 않음

UNCHECKED,ERROR,INVALID는 유효성 검사 실패로 표시됨
validationResult.message string Validation 세부 메시지로 항상 응답되는 값은 아님
convertedImageInfo JSON object 이미지 포맷이 pdf 또는 tiff인 경우 응답
좌표값은 이미지로 변환된 호출 파일을 기준으로 함.
convertedImageInfo.width integer 변환 이미지 가로 길이
convertedImageInfo.height integer 변환 이미지 세로 길이
convertedImageInfo.pageIndex integer pdf 또는 tiff의 페이지 인덱스
combineResult JSON object 판독 결과 결합
combineResult.name string 결합 필드 이름
combineResult.text string 각 필드별 출력값 및 고정 텍스트
tables JSON array object ImageTable Object 객체 참조

2. ImageField 객체 필드

필드명 유형 설명
name string 요청 바디의 images.name에 입력한 이미지명
valueType string 입력값 유형
ALL: 텍스트와 숫자
NUMERIC:숫자
inferText string 인식된 텍스트 값
type 필드의 값이 CHECKBOX인 경우 설정에서 지정한 응답값으로 대체됨
inferConfidence float 인식한 텍스트에 대한 신뢰도를 0~1 사이로 나타내며 값이 클수록 정확도가 높음
boundingPoly JSON array object boundingPoly 객체 참조
type string 인식된 이미지의 유형
NORMAL: 일반
MULTI_BOX: 멀티박스
CHECKBOX: 체크박스
checked boolean 체크박스 내 체크 여부를 표시
type 필드가 CHECKBOX인 경우만 지원
true: 체크되어 있음
false: 체크되어 있지 않음
lineBreak boolean 인식된 텍스트의 마지막 줄 여부를 표시
General OCR 호출 시에만 확인 가능
true: 마지막 텍스트
false: 마지막 텍스트 아님
subFields JSON Array SubField 객체 참조.
Template OCR 호출 시에만 확인 가능

3. boundingPoly 객체 필드

필드명 유형 설명
vertices JSON array object vertices 객체 참조

4. vertices 객체 필드

필드명 유형 설명
x float x축 좌표값
y float y축 좌표값

5. SubField Object 객체 필드

필드명 유형 설명
boundingPoly JSON array object boundingPoly 객체 참조
inferText string 인식된 텍스트 값
inferConfidence float 인식한 텍스트에 대한 신뢰도를 0~1 사이로 나타내며 값이 클수록 정확도가 높음
lineBreak boolean 인식된 텍스트의 마지막 줄 여부를 표시
true: 마지막 텍스트
false: 마지막 텍스트 아님

응답 바디 (V1)

Template OCR 요청 바디의 version을 V1로 설정했을 때의 응답 바디를 설명합니다.

1. 응답 바디 필드

필드명 유형 설명
uid string API의 유효성을 검사하기 위해 제공되는 고유 ID로, 유효성 검사 요청을 추적하는 데 사용
name string 요청 바디의 images.name에 입력한 이미지명
inferResult string 이미지 인식 결과
SUCCESS: 이미지 인식 성공
FAILURE: 이미지 인식 실패
ERROR: 이미지 인식 처리예외
message string 이미지 인식 결과에 대한 세부사항
성공 시 SUCCESS 표시
이미지 인식 실패 시 오류 메시지 표시
title string 이미지 타이틀
fields JSON array object ImageField 객체 참조
validationResult JSON object 유효성 검사 결과
validationResult.result string 유효성 검사 결과 코드
NO_REQUESTED: 검증 작업을 요청하지 않음
UNCHECKED: 동작 응답이 확인되지 않거나 응답 미수락
ERROR: 검증 실행에 오류 발생
VALID: 검증 결과가 유효함
INVALID: 검증 결과가 유효하지 않음

UNCHECKED,ERROR,INVALID는 유효성 검사 실패로 표시됨
validationResult.message string Validation 세부 메시지로 항상 표시되는 값은 아님
combineResult JSON object 판독 결과 결합
combineResult.name string 결합 필드 이름
combineResult.text string 각 필드별 출력값 및 고정 텍스트

2. ImageField 객체 필드

필드명 유형 설명
name string 요청 바디의 images.name에 입력한 이미지명
valueType string 필드의 텍스트 값 유형을 나타내며 텍스트 유형에 따라 표시되지 않을 수 있음
ALL: 텍스트와 숫자
inferText string 인식된 텍스트 값
inferConfidence float 인식한 텍스트에 대한 신뢰도를 0~1 사이로 나타내며 값이 클수록 정확도가 높음
bounding JSON array object bounding 객체 참조

3. bounding 객체 필드

필드명 유형 설명
top Float Bounding y축 좌표 값
left Float Bounding x축 좌표 값
width Float Bounding y축 가로
height Float Bounding y축 세로

API 예제

다음은 각 언어별 CLOVA OCR API 구현 예제입니다

multipart/form-data 요청 예제

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
 
import org.json.JSONArray;
import org.json.JSONObject;
 
public class OCRGeneralAPIDemo {
 
    public static void main(String[] args) {
        String apiURL = "YOUR_API_URL";
        String secretKey = "YOUR_SECRET_KEY";
        String imageFile = "YOUR_IMAGE_FILE";
 
        try {
            URL url = new URL(apiURL);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setUseCaches(false);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setReadTimeout(30000);
            con.setRequestMethod("POST");
            String boundary = "----" + UUID.randomUUID().toString().replaceAll("-", "");
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            con.setRequestProperty("X-OCR-SECRET", secretKey);
 
            JSONObject json = new JSONObject();
            json.put("version", "V2");
            json.put("requestId", UUID.randomUUID().toString());
            json.put("timestamp", System.currentTimeMillis());
            JSONObject image = new JSONObject();
            image.put("format", "jpg");
            image.put("name", "demo");
            JSONArray images = new JSONArray();
            images.put(image);
            json.put("images", images);
            String postParams = json.toString();
 
            con.connect();
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            long start = System.currentTimeMillis();
            File file = new File(imageFile);
            writeMultiPart(wr, postParams, file, boundary);
            wr.close();
 
            int responseCode = con.getResponseCode();
            BufferedReader br;
            if (responseCode == 200) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            } else {
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
 
            System.out.println(response);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
 
    private static void writeMultiPart(OutputStream out, String jsonMessage, File file, String boundary) throws
        IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("--").append(boundary).append("\r\n");
        sb.append("Content-Disposition:form-data; name=\"message\"\r\n\r\n");
        sb.append(jsonMessage);
        sb.append("\r\n");
 
        out.write(sb.toString().getBytes("UTF-8"));
        out.flush();
 
        if (file != null && file.isFile()) {
            out.write(("--" + boundary + "\r\n").getBytes("UTF-8"));
            StringBuilder fileString = new StringBuilder();
            fileString
                .append("Content-Disposition:form-data; name=\"file\"; filename=");
            fileString.append("\"" + file.getName() + "\"\r\n");
            fileString.append("Content-Type: application/octet-stream\r\n\r\n");
            out.write(fileString.toString().getBytes("UTF-8"));
            out.flush();
 
            try (FileInputStream fis = new FileInputStream(file)) {
                byte[] buffer = new byte[8192];
                int count;
                while ((count = fis.read(buffer)) != -1) {
                    out.write(buffer, 0, count);
                }
                out.write("\r\n".getBytes());
            }
 
            out.write(("--" + boundary + "--\r\n").getBytes("UTF-8"));
        }
        out.flush();
    }
}
import requests
import uuid
import time
import json
 
api_url = 'YOUR_API_URL'
secret_key = 'YOUR_SECRET_KEY'
image_file = 'YOUR_IMAGE_FILE'
 
request_json = {
    'images': [
        {
            'format': 'jpg',
            'name': 'demo'
        }
    ],
    'requestId': str(uuid.uuid4()),
    'version': 'V2',
    'timestamp': int(round(time.time() * 1000))
}
 
payload = {'message': json.dumps(request_json).encode('UTF-8')}
files = [
  ('file', open(image_file,'rb'))
]
headers = {
  'X-OCR-SECRET': secret_key
}
 
response = requests.request("POST", api_url, headers=headers, data = payload, files = files)
 
print(response.text.encode('utf8'))
 
<?php
  $client_secret = "YOUR_SECRET_KEY";
  $url = "YOUR_API_URL";
  $image_file = "YOUR_IMAGE_FILE";
 
  $params->version = "V2";
  $params->requestId = uniqid();
  $params->timestamp = time();
  $image->format = "jpg";
  $image->name = "demo";
  $images = array($image);
  $params->images = $images;
  $json = json_encode($params);
   
  $boundary = uniqid();
  $is_post = true;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, $is_post);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $post_form = array("message" => $json, "file" => new CURLFILE($image_file));
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post_form);
  $headers = array();
  $headers[] = "X-OCR-SECRET: ".$client_secret;
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  $response = curl_exec($ch);
  $err = curl_error($ch);
  $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close ($ch);
 
  echo $status_code;
  if($status_code == 200) {
    echo $response;
  } else {
    echo "ERROR: ".$response;
  }
?>
const FormData = require('form-data')
const axios = require('axios')
 
function requestWithBase64 () {
  axios
    .post(
      '', // APIGW Invoke URL
      {
        images: [
          {
            format: '', // file format
            name: '', // image name
            data: '' // image base64 string(only need part of data). Example: base64String.split(',')[1]
          }
        ],
        requestId: '', // unique string
        timestamp: 0,
        version: 'V2'
      },
      {
        headers: {
          'X-OCR-SECRET': '' // Secret Key
        }
      }
    )
    .then(res => {
      if (res.status === 200) {
        console.log('requestWithBase64 response:', res.data)
      }
    })
    .catch(e => {
      console.warn('requestWithBase64 error', e.response)
    })
}
 
function requestWithFile () {
  const file = '' // image file object. Example: fs.createReadStream('./example.png')
  const message = {
    images: [
      {
        format: '', // file format
        name: '' // file name
      }
    ],
    requestId: '', // unique string
    timestamp: 0,
    version: 'V2'
  }
  const formData = new FormData()
 
  formData.append('file', file)
  formData.append('message', JSON.stringify(message))
 
  axios
    .post(
      '', // APIGW Invoke URL
      formData,
      {
        headers: {
          'X-OCR-SECRET': '', // Secret Key
          ...formData.getHeaders()
        }
      }
    )
    .then(res => {
      if (res.status === 200) {
        console.log('requestWithFile response:', res.data)
      }
    })
    .catch(e => {
      console.warn('requestWithFile error', e.response)
    })
}

application/json 요청 예제

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
 
import org.json.JSONArray;
import org.json.JSONObject;
 
public class OCRGeneralAPIDemo {
 
    public static void main(String[] args) {
        String apiURL = "YOUR_API_URL";
        String secretKey = "YOUR_SECRET_KEY";
 
        try {
            URL url = new URL(apiURL);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setUseCaches(false);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            con.setRequestProperty("X-OCR-SECRET", secretKey);
 
            JSONObject json = new JSONObject();
            json.put("version", "V2");
            json.put("requestId", UUID.randomUUID().toString());
            json.put("timestamp", System.currentTimeMillis());
            JSONObject image = new JSONObject();
            image.put("format", "jpg");
            image.put("url", "https://kr.object.ncloudstorage.com/ocr-ci-test/sample/1.jpg"); // image should be public, otherwise, should use data
            // FileInputStream inputStream = new FileInputStream("YOUR_IMAGE_FILE");
            // byte[] buffer = new byte[inputStream.available()];
            // inputStream.read(buffer);
            // inputStream.close();
            // image.put("data", buffer);
            image.put("name", "demo");
            JSONArray images = new JSONArray();
            images.put(image);
            json.put("images", images);
            String postParams = json.toString();
 
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(postParams);
            wr.flush();
            wr.close();
 
            int responseCode = con.getResponseCode();
            BufferedReader br;
            if (responseCode == 200) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            } else {
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
 
            System.out.println(response);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
 
}
 
import requests
import uuid
import time
import base64
import json
 
api_url = 'YOUR_API_URL'
secret_key = 'YOUR_SECRET_KEY'
image_url = 'YOUR_IMAGE_URL'
# image_file = 'YOUR_IMAGE_FILE'
# with open(image_file,'rb') as f:
#     file_data = f.read()
 
request_json = {
    'images': [
        {
            'format': 'jpg',
            'name': 'demo',
#             'data': base64.b64encode(file_data).decode()
            'url': image_url
        }
    ],
    'requestId': str(uuid.uuid4()),
    'version': 'V2',
    'timestamp': int(round(time.time() * 1000))
}
 
payload = json.dumps(request_json).encode('UTF-8')
headers = {
  'X-OCR-SECRET': secret_key,
  'Content-Type': 'application/json'
}
 
response = requests.request("POST", api_url, headers=headers, data = payload)
 
print(response.text)
 
<?php
  $client_secret = "YOUR_SECRET_KEY";
  $url = "YOUR_API_URL";
  $image_url = "YOUR_IMAGE_URL";
  // $image_file = "YOUR_IMAGE_FILE";
 
  $params->version = "V2";
  $params->requestId = "uuid";
  $params->timestamp = time();
  $image->format = "jpg";
  $image->url = $image_url;
  // $image->data = base64_encode(file_get_contents($image_file));
  $image->name = "demo";
  $images = array($image);
  $params->images = $images;
  $json = json_encode($params);
 
  $is_post = true;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, $is_post);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
  $headers = array();
  $headers[] = "X-OCR-SECRET: ".$client_secret;
  $headers[] = "Content-Type:application/json; charset=utf-8";
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  $response = curl_exec($ch);
  $err = curl_error($ch);
  $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close ($ch);
 
  echo $status_code;
  if($status_code == 200) {
    echo $response;
  } else {
    echo "ERROR: ".$response;
  }
?>
 
<%
Function ASPPostJSON()
    Dim objXmlHttp
    Set objXmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
    url = "YOUR_INVOKE_URL"
    secret = "YOUR_SECRET_KEY"
    base64 = """"+ToBase64(getBinaryFile(Server.MapPath("test.jpg")))+""""
    body = "{""images"":[{""format"":""jpg"",""name"":""test 1"",""data"":"+base64+"}],""requestId"":""string"",""timestamp"":0,""version"":""V2"",""lang"":""ko""}"
    objXmlHttp.Open "POST", url, False
    objXmlHttp.SetRequestHeader "Content-Type", "application/json"
    objXmlHttp.SetRequestHeader "X-OCR-SECRET", secret
 
    objXmlHttp.Send body
 
    ASPPostJSON = CStr(objXmlHttp.ResponseText)
 
    Response.write(ASPPostJSON)
    Set objXmlHttp = Nothing
 
End Function
 
Function getBinaryFile(strFilePath)
  Dim TypeBinary, oStream
 
  TypeBinary = 1
 
  Set oStream = Server.CreateObject("ADODB.Stream")
 
  oStream.Open
 
  oStream.Type = TypeBinary
  oStream.LoadFromFile strFilePath
 
  getBinaryFile = oStream.read
 
  Set oStream = Nothing
 
End Function
 
Function ToBase64(rabyt)
 
     Dim xml: Set xml = CreateObject("MSXML2.DOMDocument.3.0")
     xml.LoadXml "<root />"
     xml.documentElement.dataType = "bin.base64"
     xml.documentElement.nodeTypedValue = rabyt
 
     ToBase64 = xml.documentElement.Text
 
End Function
 
call ASPPostJSON()
%>