CLOVA OCR Document API
  • PDF

CLOVA OCR Document API

  • PDF

version

Version Date Changes
v1.0.0 2021-03-04 최초 작성
v1.0.1 2021-05-19 add medical receipt
v1.0.2 2021-07-22 foundValuesSum -> foundValueSum
add maskingPolys in IDCard
v1.0.3 2021-09-16 add Alien Registration card in IDCard

요청

Method Request URI
POST CLOVA OCR 빌더에서 생성된 API Gateway의 InvokeURL로 호출함
각 도메인마다 고유의 호출 URL이 생성됨

Requesting document OCR recognition

구분 설명 Path
Document 영수증 /document/receipt
Document 신용카드 /document/credit-card
Document 명함 /document/name-card
Document 사업자등록증 /document/biz-license
Document 신분증(주민등록증, 운전면허증, 여권, 외국인등록증) /document/id-card
Document 의료 영수증 /document/medical-receipt

요청 헤더

헤더명 설명
X-OCR-SECRET 도메인에서 API Gateway 연동시 생성한 X-OCR-SECRET:{Client Secret}
Content-Type application/json : request use json body. Support image.data encoded with base64.
- multipart/form-data : request use multipart form body. Support image file transferred as stream.

요청 바디

Content-Type : application/json

  1. 이미지 인식 요청
구분 Json Model
이미지 인식 요청 {
"version": "string",
"requestId": "string",
"timestamp": 0,
"images": [{ "format": "string", "data": "string", "name": "string"}]
}

이미지 인식 요청 필드 상세 설명

필드명 필수 여부 타입 설명 제약 사항
version Yes string "V2"로 고정
requestId Yes string API 호출 UUID
timestamp Yes 0 API 호출 Timestamp 값
images Yes string Json array로 입력
현재는 1개의 이미지 입력만 허용 (한국어/일본어)
images.format Yes string 이미지 포맷을 설정 “jpg”, “jpeg”, “png” 이미지,"pdf","tiff" 단일 페이지 형식을 지원
image.data Yes string image.data는 base64 인코딩 이미지 바이트
image.name Yes string 이미지 명 입력
이미지를 식별 및 응답 결과 확인에 사용됨

CURL example:

curl --request POST 'your apigw invoke url' \
--header 'X-OCR-SECRET: your secret key' \
--data-raw '{"images":[{"format":"jpg","name":"demo","data":"your image base64 bytes"}],"requestId":"guide-json-demo","version":"V2","timestamp":1584062336793}'

Content-Type : multipart/form-data

  1. 이미지 인식 요청
KEY Required VALUE
message Y {"version": "string","requestId": "string","timestamp": 0,"images": [{ "format": "string", "name": "string" }]}
file Y image file steam data

Form Data Message Value Description

Field name Required Type Description Constraints
version Yes string "V2"로 고정
requestId Yes string API 호출 UUID.
timestamp Yes integer API 호출 Timestamp 값
images Yes string It is entered as Json array and currently only one image input is allowed.
images.format Yes string 이미지 포맷을 설정 “jpg”, “jpeg”, “png” 이미지 ,"pdf","tiff" 단일 페이지형식을 지원함
image.name Yes string 이미지 명 입력
이미지를 식별 및 응답 결과 확인에 사용됨

CURL example:

curl --request POST 'your apigw invoke url' \
--header 'X-OCR-SECRET: your secret key' \
--form 'message={"images":[{"format":"png","name":"demo"}],"requestId":"guide-demo","version":"V2","timestamp":1584062336793}' \
--form 'file=@image.png'

응답

응답 바디

  1. Image Recognition Results
Classification Json Model
Image Recognition Results {
"uid": "string",
"name": "string",
"inferResult": "string",
"message": "string",
"receipt": {},
"creditCard": {},
"bizLicense": {},
"idCard": {},
"nameCard": {},
"validationResult": { "result": "string", "message": "string"}
}

Detailed description of the Image Recognition Results field

Field Name Data Type Description
uid string A unique ID that is provided to validate the API, which is used to track validation requests.
name string The requested image name.
inferResult string Image inference result.
"SUCCESS": Image recognition successful. “FAILURE”: Image recognition failed.“ERROR”: Image recognition exception.
message string Successful image recognition, "SUCCESS"
If image recognition fails, an error message is displayed.
Error messages are detailed at the bottom
receipt json object receipt object reference
creditCard json object creditCard object reference
bizLicense json object bizLicense object reference
idCard json object idCard object reference
nameCard json object nameCard object reference
validationResult json object Validation result.
validationResult.result string Result Code.
“NO_REQUESTED”: The validation task did not run.
“UNCHECKED”: Action response not confirmed or not accepted
“ERROR”: Error executing validation.
“VALID”: The verification result is valid.
“INVALID”: The verification result is invalid.
“UNCHECHED”,“ERROR” and “INVALID” are marked as validation failures.
validationResult.message string It is not always the value that is returned in the Validation detail message.
convertedImageInfo json object Only response when image format is pdf/tiff.
Coordinates are based on converted image when request format is pdf/tiff.
convertedImageInfo.width integer The base image width.
convertedImageInfo.height integer The base image height.
convertedImageInfo.pageIndex integer The page index of pdf/tiff
  1. receipt object
Classification Json Model
receipt Field {
"meta": {},
"result": {},
}

Receipt Object Field Details

Field Name Data Type Description
meta json object Meta information | 메타 정보
meta.estimatedLanguage string The language estimated by OCR (en: English, ja: Japanese, ko: Korean) | OCR 인식 언어
result json object Recognition result | 인식 결과
result.storeInfo json object Store information | 매장 정보
result.storeInfo.poiInfo PoiObject[] Place-of-interest (POI) grounding result | POI 그라운딩 결과
result.storeInfo.name StringObject Name of the store | 상호명
result.storeInfo.subName StringObject Branch name of the store | 지점명
result.storeInfo.bizNum StringObject Business number of the store | 사업자번호
result.storeInfo.movieName StringObject Movie name | 영화 제목 (영화표 관련 항목)
result.storeInfo.addresses StringObject[] Address of the store | 매장 주소
result.storeInfo.tel TelObject[] Telephone number of the store
result.paymentInfo json object Payment Information | 결제 정보
result.paymentInfo.date DateObject Transaction date | 결제 날짜
result.paymentInfo.time TimeObject Transaction time | 결제 시간
result.paymentInfo.cardInfo json object Transaction card information
result.paymentInfo.cardInfo.company StringObject Name of the card company | 카드사 이름
result.paymentInfo.cardInfo.number StringObject Card number | 카드 번호
result.paymentInfo.confirmNum BaseObject Transaction confirmation number | 결제 번호
result.subResults json array Sub results | 항목 그룹 정보
result.subResults.items json array Item list | 인식된 항목 정보 (메뉴 등)
result.subResults.items.name StringObject Item name | 항목명
result.subResults.items.code StringObject Item code | 항목 코드
result.subResults.items.count FloatObject Item quantity | 항목 수량
result.subResults.items.price json object Item price information | 가격정보
result.subResults.items.price.price FloatObject Price of the item | 가격
result.subResults.items.price.unitPrice FloatObject Unit price of the item | 단가
result.totalPrice json object Total information | 총 금액 정보
result.totalPrice.price FloatObject Total price | 총 금액
  1. creditCard object
Classification Json Model
receipt Field {
"meta": {},
"result": {},
}

creditCard Object Field Details

Field Name Data Type Description
meta json object Meta information
meta.estimatedLanguage string The language estimated by OCR (en: English, ja: Japanese, ko: Korean)
result json object Recognition result
result.number Field object Field object reference
result.validThru Field object Field object reference
  1. bizLicense object
Classification Json Model
receipt Field {
"meta": {},
"result": {},
}

bizLicense Object Field Details

Field Name Data Type Description
meta json object Meta information
meta.estimatedLanguage string The language estimated by OCR (en: English, ja: Japanese, ko: Korean)
result json object Recognition result
result.birth BaseObject[] Date of birth
result.bisAddress BaseObject[] Business Address
result.bisArea BaseObject[] Area of business establishment
result.bisItem BaseObject[] Business item
result.registerNumber BaseObject[] Business register number
result.bisType BaseObject[] Business type
result.companyName BaseObject[] Name of company
result.coRepName BaseObject[] Name of co-representatives
result.corpName BaseObject[] Name of corporate (group)
result.corpRegisterNum BaseObject[] Business registration number
result.coRepSocialNum BaseObject[] Resident registration number of co-representatives
result.documentType StringObject[] Document type
result.headAddress BaseObject[] Head office address
result.issuanceDate BaseObject[] Date of issuance
result.issuanceReason BaseObject[] Reason for issuance
result.openDate BaseObject[] Date of business commencement
result.repName BaseObject[] Name of representative
result.socialNumber BaseObject[] Resident registration number
result.taxType BaseObject[] Type of taxation
  1. idCard object
Classification Json Model
receipt Field {
"meta": {},
"result": {},
}

idCard Object Field Details

Field Name Data Type Description
meta json object Meta information
meta.estimatedLanguage string The language estimated by OCR (en: English, ja: Japanese, ko: Korean)
result json object Recognition result
result.isConfident boolean Indicator reflecting qualifications for reliability
If required details exist for each type of ID, it is output as True, otherwise it is output as False.
result.IDType string Type of ID
Return value is one of "ID Card", "Driver's License", "Passport", and "unknown".
result.ic json object National ID card information
result.ic.name StringObject[] Name (Korean)
result.ic.personalNum StringObject[] Personal ID number
result.ic.address StringObject[] Address
result.ic.issueDate DateObject[] Issued date
result.ic.authority StringObject[] Issuing agency
result.dl json object Driver's license card information
result.dl.type BaseObject[] License type
result.dl.num StringObject[] License number
result.dl.name StringObject[] Name (Korean)
result.dl.personalNum StringObject[] Personal number
result.dl.address StringObject[] Address
result.dl.renewStartDate DateObject[] Start date of the renewal period
result.dl.renewEndDate DateObject[] End date of the renewal period
result.dl.condition StringObject[] License conditions
result.dl.code StringObject[] License code
result.dl.organDonation BaseObject[] Registration for organ and tissue donation
result.dl.issueDate DateObject[] Issued date
result.dl.authority StringObject[] Issuing agency
result.pp json object Passport information
result.pp.type StringObject[] Passport type
result.pp.issueCountry BaseObject[] Issuing country
result.pp.num StringObject[] Passport number
result.pp.surName StringObject[] Surname
result.pp.givenName StringObject[] Given names
result.pp.nationality StringObject[] Nationality
result.pp.birthDate DateObject[] Date of birth
result.pp.personalNum StringObject[] Personal ID number
result.pp.sex StringObject[] Sex
result.pp.issueDate DateObject[] Date of issue
result.pp.expireDate DateObject[] Date of expiry
result.pp.authority BaseObject[] Issuing authority
result.pp.fullNameKor StringObject[] Name (Korean)
result.pp.MRZ1 StringObject[] Machine Readable Zone (MRZ) 1
result.pp.MRZ2 StringObject[] Machine Readable Zone (MRZ) 2
result.ac json object Alien Registration card information
result.ac.alienRegNum StringObject[] Alien Registration number
result.ac.sex StringObject[] Sex
result.ac.name StringObject[] Name
result.ac.nationality StringObject[] Nationality
result.ac.visaType StringObject[] Visa Type
result.ac.issueDate DateObject[] Issued date
result.ac.authority StringObject[] Issuing agency
result.ac.authorityEng StringObject[] Issuing agency (English)
result.ac.alienRegNumEtc StringObject[] Alien Resgistration number Etc
  1. nameCard object
Classification Json Model
receipt Field {
"meta": {},
"result": {},
}

nameCard Object Field Details

Field Name Data Type Description
meta json object Meta information
meta.estimatedLanguage string The language estimated by OCR (en: English, ja: Japanese, ko: Korean)
result json object Recognition result
result.name StringObject[] Name information
result.nameFurigana StringObject[] Furigana name information (Only response when language is ja)
result.company StringObject[] Company information
result.department StringObject[] Department information
result.address StringObject[] Address information
result.position StringObject[] Position information
result.mobile TelObject[] Mobile information
result.tel TelObject[] Tel information
result.fax TelObject[] Fax information
result.email StringObject[] Email information
result.homepage StringObject[] Homepage information
  1. field object
Classification Json Model
receipt Field {
"text": "",
"confidence": 0.0,
"boundingPoly": {},
"subBoundingPolys": []
}

field Object Field Details

Field Name Data Type Description
text string Recognition Result Text
confidence float Confidence of infer result. Larger values of 0-1 are more accurate.
boundingPoly BoundingPoly object boundingPoly Object reference
subBoundingPolys BoundingPoly[] boundingPoly Object reference
  1. boundingPoly object
Classification Json Model
boundingPoly {
"vertices":[{}]
}

boundingPoly Object Field Details

Field Name Data Type Description
vertices vertices object vertices object reference
  1. vertices object
Classification Json Model
vertices {
"x": 0.0,
"y": 0.0
}

vertices Object Field Details

Field Name Data Type Description
x float X coodinate
y float y coodinate
  1. baseObject
Classification Json Model
baseObject {
"text": "",
"boundingPolys": []
}

baseObject Field Details

Field Name Data Type Description
text string parsed text
boundingPolys BoundingPoly[] boundingPoly Object reference
  1. dateObject
Classification Json Model
baseObject {
"text": "",
"formatted": {},
"boundingPolys": []
}

dateObject Field Details

Field Name Data Type Description
text string parsed text
formatted json object Additional information for the parsed text
formatted.year string Year. It indicates a four-digit year. It follows the ISO 8601 standard form, except that it can be an empty string.
formatted.month string Month. It indicates a two-digit month. It follows the ISO 8601 standard form, except that it can be an empty string.
formatted.day string Day. It indicates a two-digit day. It follows the ISO 8601 standard form, except that it can be an empty string.
boundingPolys BoundingPoly[] boundingPoly Object reference
  1. timeObject
Classification Json Model
baseObject {
"text": "",
"formatted": {},
"boundingPolys": [],
"maskingPolys": []
}

timeObject Field Details

Field Name Data Type Description
text string parsed text
formatted json object Additional information for the parsed text
formatted.hour string Hour. It indicates a two-digit hour. It follows the ISO 8601 standard form, except that it can be an empty string.
formatted.minute string Minute. It indicates a two-digit minute. It follows the ISO 8601 standard form, except that it can be an empty string.
formatted.second string Second. It indicates a two-digit second. It follows the ISO 8601 standard form, except that it can be an empty string.
boundingPolys BoundingPoly[] boundingPoly Object reference
maskingPolys BoundingPoly[] masking personal information
  1. TelObject
Classification Json Model
baseObject {
"text": "",
"formatted": {},
"boundingPolys": []
}

TelObject Field Details

Field Name Data Type Description
text string parsed text
formatted json object Additional information for the parsed text
formatted.value string Formatted text to indicate the type of telephone number. It has a form of string of numbers primarily, but can have telephone prefix (+). It can be an empty string when refinement fails.
boundingPolys BoundingPoly[] boundingPoly Object reference
  1. FloatObject
Classification Json Model
baseObject {
"text": "",
"formatted": {},
"boundingPolys": []
}

FloatObject Field Details

Field Name Data Type Description
text string parsed text
formatted json object Additional information for the parsed text
formatted.value string Formatted text to indicate the type of float. It has the type of a string of float number. It can be useful to describe count and price of an item. It can be an empty string when refinement fails.
boundingPolys BoundingPoly[] boundingPoly Object reference
  1. StringObject
Classification Json Model
baseObject {
"text": "",
"formatted": {},
"boundingPolys": [],
"maskingPolys": []
}

StringObject Field Details

Field Name Data Type Description
text string parsed text
formatted json object Additional information for the parsed text
formatted.value string The refined text of the text. The refining process depends on the categories of each ID. It can be an empty string.
boundingPolys BoundingPoly[] boundingPoly Object reference
maskingPolys BoundingPoly[] personal information
  1. PoiObject
Classification Json Model
baseObject {
"gid": "",
"title": "",
"phone": "",
"address": "",
"roadAddress": "",
"biznum": "",
"confidence": ""
}

PoiObject Field Details

Field Name Data Type Description
gid string unique id
title string 상호명
phone string 전화번호
address string 주소
roadAddress string 도로명주소
biznum string 사업자번호(아직 정식으로 지원되지 않아 null일 수 있으나 추후 추가될 수 있음)
confidence string confidence(높을 수록 정확도가 높음)
  1. medicalReceipt object
Classification Json Model
medicalReceipt {
"checksum": {},
"result": []
}

medicalReceipt Object Field Details

Field Name Data Type Description
checksum json object Checksum results
checksum.sumPaidByPatient Checksum 본인부담금 합계
checksum.sumPaidByInsurer Checksum 공단부담금 합계
checksum.sumPaidByPatientFull Checksum 전액본인부담금 합계
checksum.sumTreatmentCostEtc Checksum 선택진료료 합계
checksum.sumTreatmentCostEtc Checksum 선택진료료이외 합계
checksum.totalAmount Checksum 총액확인
checksum.totalPaid Checksum 환자부담액
result MedicalReceiptResult[] List of value cell results

18.Checksum object

Classification Json Model
checksum Field {
"found": "",
"foundValueIds": [],
"foundValueSum": "",
"foundTotalIds": [],
"foundTotalSum": "",
"foundTotalSum": ""
}

Checksum Object Field Details

Field Name Data Type Description
found json object Flag indicating whether any of the checksum field is found
foundValueIds int[] ID List of the found value cell
foundValueSum float Sum of the value found
foundTotalIds int[] ID List of the found total cell
foundTotalSum float Sum of the total values found
difference float Difference between value and total cell

19.MedicalReceiptResult object

Classification Json Model
result {
"id": "",
"keyTexts": "",
"valueText": "",
"confidence": "",
"keyCells": [],
"valueCell": {}
}

MedicalReceiptResult Object Field Details

Field Name Data Type Description
id int ID of the cell
keyTexts string Key string texts separated using the “
valueText string Text in the value cell
confidence float Value cell confidence
keyCells KeyCell[] List of key cell objects in columns - rows key order
valueCell ValueCell Value cell object

20.KeyCell object

Classification Json Model
KeyCell Field {
"boundingPoly": {},
"depth": "",
"formatted": "",
"group": "",
"value": ""
}

KeyCell Object Field Details

Field Name Data Type Description
boundingPoly BoundingPoly Cell bounding box coordinate
depth string Depth of the found key cell
formatted string Grounded text in the key cell
group string Identifier to distinguish column/row-wise key
value string Ungrounded text in the key cell

21.ValueCell object

Classification Json Model
ValueCell Field {
"boundingPoly": {},
"confidence": "",
"value": ""
}

ValueCell Object Field Details

Field Name Data Type Description
boundingPoly BoundingPoly Cell bounding box coordinate
confidence float Value cell confidence
value string Text in the value cell

예시

DOCUMENT OCR 요청 예시

{
  "version": "V2",
  "requestId": "string",
  "timestamp": 0,
  "images": [
    {
      "format": "jpg",
      "name": "test 1",
      "data": "data"
    }
  ]
}

Credit Card 응답 예시

{
    "version": "V2",
    "requestId": "string",
    "timestamp": 1613984515468,
    "images": [
        {
            "creditCard": {
                "result": {
                    "number": {
                        "text": "5307123456749012",
                        "confidence": 0.96435016,
                        "boundingPoly": {
                            "vertices": [
                                {
                                    "x": 64.0,
                                    "y": 218.0
                                },
                                {
                                    "x": 582.0,
                                    "y": 222.0
                                },
                                {
                                    "x": 582.0,
                                    "y": 265.0
                                },
                                {
                                    "x": 64.0,
                                    "y": 261.0
                                }
                            ]
                        },
                        "subBoundingPolys": [
                            {
                                "vertices": [
                                    {
                                        "x": 65.0,
                                        "y": 222.0
                                    },
                                    {
                                        "x": 175.0,
                                        "y": 225.0
                                    },
                                    {
                                        "x": 174.0,
                                        "y": 260.0
                                    },
                                    {
                                        "x": 64.0,
                                        "y": 257.0
                                    }
                                ]
                            },
                            {
                                "vertices": [
                                    {
                                        "x": 202.0,
                                        "y": 225.0
                                    },
                                    {
                                        "x": 312.0,
                                        "y": 225.0
                                    },
                                    {
                                        "x": 312.0,
                                        "y": 262.0
                                    },
                                    {
                                        "x": 202.0,
                                        "y": 262.0
                                    }
                                ]
                            },
                            {
                                "vertices": [
                                    {
                                        "x": 340.0,
                                        "y": 225.0
                                    },
                                    {
                                        "x": 445.0,
                                        "y": 225.0
                                    },
                                    {
                                        "x": 445.0,
                                        "y": 260.0
                                    },
                                    {
                                        "x": 340.0,
                                        "y": 260.0
                                    }
                                ]
                            },
                            {
                                "vertices": [
                                    {
                                        "x": 470.0,
                                        "y": 222.0
                                    },
                                    {
                                        "x": 582.0,
                                        "y": 222.0
                                    },
                                    {
                                        "x": 582.0,
                                        "y": 260.0
                                    },
                                    {
                                        "x": 470.0,
                                        "y": 260.0
                                    }
                                ]
                            }
                        ]
                    }
                }
            },
            "uid": "5f824ebe5b9744bb81bd3e1ef7f42e4e",
            "name": "testV2Demo",
            "inferResult": "SUCCESS",
            "message": "SUCCESS",
            "validationResult": {
                "result": "NO_REQUESTED"
            }
        }
    ]
}

Receipt 응답 예시

{
	"version": "V2",
	"requestId": "string",
	"timestamp": 1613984672273,
	"images": [{
		"receipt": {
			"meta": {
				"estimatedLanguage": "ko"
			},
			"result": {
				"storeInfo": {
					"name": {
						"text": "emart everyday",
						"formatted": {
							"value": "emart everyday"
						},
						"boundingPolys": [{
							"vertices": [{
									"x": 263.0,
									"y": 96.0
								},
								{
									"x": 390.0,
									"y": 100.0
								},
								{
									"x": 389.0,
									"y": 141.0
								},
								{
									"x": 262.0,
									"y": 137.0
								}
							]
						}]
					},
					"subName": {
						"text": "분당정지2점",
						"formatted": {
							"value": "분당정지2점"
						},
						"boundingPolys": [{
							"vertices": [{
									"x": 530.0,
									"y": 102.0
								},
								{
									"x": 611.0,
									"y": 102.0
								},
								{
									"x": 611.0,
									"y": 122.0
								},
								{
									"x": 530.0,
									"y": 122.0
								}
							]
						}]
					},
					"bizNum": {
						"text": "212-81-25544",
						"formatted": {
							"value": "212-81-25544"
						},
						"boundingPolys": [{
							"vertices": [{
									"x": 402.0,
									"y": 125.0
								},
								{
									"x": 515.0,
									"y": 124.0
								},
								{
									"x": 515.0,
									"y": 141.0
								},
								{
									"x": 402.0,
									"y": 142.0
								}
							]
						}]
					},
					"addresses": [{
						"text": "경기 성남시분당구 정자일로 120",
						"formatted": {
							"value": "경기 성남시분당구 정자일로 120"
						},
						"boundingPolys": [{
							"vertices": [{
									"x": 401.0,
									"y": 144.0
								},
								{
									"x": 432.0,
									"y": 144.0
								},
								{
									"x": 432.0,
									"y": 165.0
								},
								{
									"x": 401.0,
									"y": 165.0
								}
							]
						}]
					}],
					"tel": [{
						"text": "(031)786-1171",
						"formatted": {
							"value": "0317861171"
						},
						"boundingPolys": [{
							"vertices": [{
									"x": 569.0,
									"y": 122.0
								},
								{
									"x": 716.0,
									"y": 118.0
								},
								{
									"x": 716.0,
									"y": 140.0
								},
								{
									"x": 570.0,
									"y": 144.0
								}
							]
						}]
					}]
				},
				"paymentInfo": {
					"date": {
						"text": "2020-04-16",
						"formatted": {
							"year": "2020",
							"month": "04",
							"day": "16"
						},
						"boundingPolys": [{
							"vertices": [{
									"x": 261.0,
									"y": 256.0
								},
								{
									"x": 432.0,
									"y": 260.0
								},
								{
									"x": 431.0,
									"y": 284.0
								},
								{
									"x": 260.0,
									"y": 280.0
								}
							]
						}]
					},
					"time": {
						"text": "20: 11",
						"formatted": {
							"hour": "20",
							"minute": "11",
							"second": "00"
						},
						"boundingPolys": [{
							"vertices": [{
									"x": 437.0,
									"y": 261.0
								},
								{
									"x": 468.0,
									"y": 261.0
								},
								{
									"x": 468.0,
									"y": 279.0
								},
								{
									"x": 437.0,
									"y": 279.0
								}
							]
						}]
					},
					"cardInfo": {
						"company": {
							"text": "신 한",
							"formatted": {
								"value": "신한"
							},
							"boundingPolys": [{
								"vertices": [{
										"x": 309.0,
										"y": 585.0
									},
									{
										"x": 334.0,
										"y": 585.0
									},
									{
										"x": 334.0,
										"y": 610.0
									},
									{
										"x": 309.0,
										"y": 610.0
									}
								]
							}]
						},
						"number": {
							"text": "4221**8666",
							"formatted": {
								"value": "4221**8666"
							},
							"boundingPolys": [{
								"vertices": [{
										"x": 522.0,
										"y": 586.0
									},
									{
										"x": 716.0,
										"y": 592.0
									},
									{
										"x": 716.0,
										"y": 612.0
									},
									{
										"x": 522.0,
										"y": 606.0
									}
								]
							}]
						}
					},
					"confirmNum": {
						"text": "28672931",
						"boundingPolys": [{
							"vertices": [{
									"x": 522.0,
									"y": 586.0
								},
								{
									"x": 716.0,
									"y": 592.0
								},
								{
									"x": 716.0,
									"y": 612.0
								},
								{
									"x": 522.0,
									"y": 606.0
								}
							]
						}]
					}
				},
				"subResults": [{
					"items": [{
						"name": {
							"text": "씨그램 레몬350ml",
							"formatted": {
								"value": "씨그램 레몬350ml"
							},
							"boundingPolys": [{
								"vertices": [{
										"x": 310.0,
										"y": 345.0
									},
									{
										"x": 372.0,
										"y": 345.0
									},
									{
										"x": 372.0,
										"y": 369.0
									},
									{
										"x": 310.0,
										"y": 369.0
									}
								]
							}]
						},
						"count": {
							"text": "2",
							"formatted": {
								"value": "2"
							},
							"boundingPolys": [{
								"vertices": [{
										"x": 601.0,
										"y": 348.0
									},
									{
										"x": 615.0,
										"y": 348.0
									},
									{
										"x": 615.0,
										"y": 365.0
									},
									{
										"x": 601.0,
										"y": 365.0
									}
								]
							}]
						},
						"price": {
							"price": {
								"text": "1,600",
								"formatted": {
									"value": "1600"
								},
								"boundingPolys": [{
									"vertices": [{
											"x": 662.0,
											"y": 347.0
										},
										{
											"x": 716.0,
											"y": 347.0
										},
										{
											"x": 716.0,
											"y": 367.0
										},
										{
											"x": 662.0,
											"y": 367.0
										}
									]
								}]
							},
							"unitPrice": {
								"text": "800",
								"formatted": {
									"value": "800"
								},
								"boundingPolys": [{
									"vertices": [{
											"x": 541.0,
											"y": 347.0
										},
										{
											"x": 577.0,
											"y": 347.0
										},
										{
											"x": 577.0,
											"y": 368.0
										},
										{
											"x": 541.0,
											"y": 368.0
										}
									]
								}]
							}
						}
					}]
				}],
				"totalPrice": {
					"price": {
						"text": "1,600",
						"formatted": {
							"value": "1600"
						},
						"boundingPolys": [{
							"vertices": [{
									"x": 651.0,
									"y": 546.0
								},
								{
									"x": 717.0,
									"y": 548.0
								},
								{
									"x": 717.0,
									"y": 569.0
								},
								{
									"x": 651.0,
									"y": 567.0
								}
							]
						}]
					}
				}
			}
		},
		"uid": "5b9de1f9765448eca574efc1a4231bbe",
		"name": "testV2Demo",
		"inferResult": "SUCCESS",
		"message": "SUCCESS",
		"validationResult": {
			"result": "NO_REQUESTED"
		}
	}]
}

biz license 응답 예시

{
	"version": "V2",
	"requestId": "string",
	"timestamp": 1613984821070,
	"images": [{
		"bizLicense": {
			"meta": {
				"estimatedLanguage": "ko"
			},
			"result": {
				"birth": [{
					"text": "1951 년 12 03 일",
					"boundingPolys": [{
						"vertices": [{
								"x": 396.0,
								"y": 254.0
							},
							{
								"x": 421.0,
								"y": 254.0
							},
							{
								"x": 421.0,
								"y": 265.0
							},
							{
								"x": 396.0,
								"y": 265.0
							}
						]
					}]
				}],
				"bisAddress": [{
					"text": "경상남도 사천시 사천용 보공로 54",
					"boundingPolys": [{
						"vertices": [{
								"x": 193.0,
								"y": 288.0
							},
							{
								"x": 235.0,
								"y": 288.0
							},
							{
								"x": 235.0,
								"y": 300.0
							},
							{
								"x": 193.0,
								"y": 300.0
							}
						]
					}]
				}],
				"bisArea": [],
				"bisItem": [{
					"text": "비주거용 건물 임대업(점포, 자기자)",
					"boundingPolys": [{
						"vertices": [{
								"x": 368.0,
								"y": 325.0
							},
							{
								"x": 399.0,
								"y": 325.0
							},
							{
								"x": 399.0,
								"y": 334.0
							},
							{
								"x": 368.0,
								"y": 334.0
							}
						]
					}]
				}],
				"registerNumber": [{
					"text": "611-01-99810",
					"boundingPolys": [{
						"vertices": [{
								"x": 290.0,
								"y": 210.0
							},
							{
								"x": 386.0,
								"y": 211.0
							},
							{
								"x": 386.0,
								"y": 227.0
							},
							{
								"x": 290.0,
								"y": 225.0
							}
						]
					}]
				}],
				"bisType": [{
					"text": "부동산업 및 임대업",
					"boundingPolys": [{
						"vertices": [{
								"x": 221.0,
								"y": 322.0
							},
							{
								"x": 262.0,
								"y": 322.0
							},
							{
								"x": 262.0,
								"y": 333.0
							},
							{
								"x": 221.0,
								"y": 333.0
							}
						]
					}]
				}],
				"companyName": [{
					"text": "동성자동차종합정비",
					"boundingPolys": [{
						"vertices": [{
								"x": 194.0,
								"y": 232.0
							},
							{
								"x": 293.0,
								"y": 233.0
							},
							{
								"x": 293.0,
								"y": 247.0
							},
							{
								"x": 194.0,
								"y": 245.0
							}
						]
					}]
				}],
				"coRepName": [],
				"corpName": [],
				"corpRegisterNum": [],
				"coRepSocialNum": [],
				"documentType": [{
					"text": "사업자등록증",
					"formatted": {
						"value": "사업자등록증"
					},
					"boundingPolys": [{
						"vertices": [{
								"x": 199.0,
								"y": 157.0
							},
							{
								"x": 396.0,
								"y": 160.0
							},
							{
								"x": 396.0,
								"y": 189.0
							},
							{
								"x": 198.0,
								"y": 186.0
							}
						]
					}]
				}],
				"headAddress": [],
				"issuanceDate": [{
					"text": "2017 년 06 월 29일",
					"boundingPolys": [{
						"vertices": [{
								"x": 225.0,
								"y": 623.0
							},
							{
								"x": 259.0,
								"y": 623.0
							},
							{
								"x": 259.0,
								"y": 637.0
							},
							{
								"x": 225.0,
								"y": 637.0
							}
						]
					}]
				}],
				"issuanceReason": [{
					"text": "2017 년 06 월 29일",
					"boundingPolys": [{
						"vertices": [{
								"x": 225.0,
								"y": 623.0
							},
							{
								"x": 259.0,
								"y": 623.0
							},
							{
								"x": 259.0,
								"y": 637.0
							},
							{
								"x": 225.0,
								"y": 637.0
							}
						]
					}]
				}],
				"openDate": [{
					"text": "2014 년 06 월 09 일",
					"boundingPolys": [{
						"vertices": [{
								"x": 193.0,
								"y": 271.0
							},
							{
								"x": 218.0,
								"y": 271.0
							},
							{
								"x": 218.0,
								"y": 280.0
							},
							{
								"x": 193.0,
								"y": 280.0
							}
						]
					}]
				}],
				"repName": [{
					"text": "김영두",
					"boundingPolys": [{
						"vertices": [{
								"x": 193.0,
								"y": 251.0
							},
							{
								"x": 228.0,
								"y": 251.0
							},
							{
								"x": 228.0,
								"y": 264.0
							},
							{
								"x": 193.0,
								"y": 264.0
							}
						]
					}]
				}],
				"socialNumber": [],
				"taxType": [{
					"text": "일반과세자",
					"boundingPolys": [{
						"vertices": [{
								"x": 238.0,
								"y": 185.0
							},
							{
								"x": 357.0,
								"y": 187.0
							},
							{
								"x": 357.0,
								"y": 209.0
							},
							{
								"x": 238.0,
								"y": 207.0
							}
						]
					}]
				}]
			}
		},
		"uid": "ecf05843a1f444b6943e9d202475c3eb",
		"name": "testV2Demo",
		"inferResult": "SUCCESS",
		"message": "SUCCESS",
		"validationResult": {
			"result": "NO_REQUESTED"
		}
	}]
}

name card 응답 예시

{
    "version": "V2",
    "requestId": "string",
    "timestamp": 1613984872349,
    "images": [
        {
            "nameCard": {
                "meta": {
                    "estimatedLanguage": "ko"
                },
                "result": {
                    "name": [
                        {
                            "text": "홍길동",
                            "boundingPolys": [
                                {
                                    "vertices": [
                                        {
                                            "x": 286.0,
                                            "y": 194.0
                                        },
                                        {
                                            "x": 348.0,
                                            "y": 194.0
                                        },
                                        {
                                            "x": 348.0,
                                            "y": 266.0
                                        },
                                        {
                                            "x": 286.0,
                                            "y": 266.0
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    "nameFurigana": [],
                    "company": [
                        {
                            "text": "우리은행",
                            "boundingPolys": [
                                {
                                    "vertices": [
                                        {
                                            "x": 317.0,
                                            "y": 274.0
                                        },
                                        {
                                            "x": 356.0,
                                            "y": 274.0
                                        },
                                        {
                                            "x": 356.0,
                                            "y": 316.0
                                        },
                                        {
                                            "x": 317.0,
                                            "y": 316.0
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    "department": [],
                    "address": [
                        {
                            "text": "(홍길동)",
                            "boundingPolys": [
                                {
                                    "vertices": [
                                        {
                                            "x": 338.0,
                                            "y": 189.0
                                        },
                                        {
                                            "x": 414.0,
                                            "y": 189.0
                                        },
                                        {
                                            "x": 414.0,
                                            "y": 288.0
                                        },
                                        {
                                            "x": 338.0,
                                            "y": 288.0
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    "position": [
                        {
                            "text": "소장",
                            "boundingPolys": [
                                {
                                    "vertices": [
                                        {
                                            "x": 286.0,
                                            "y": 194.0
                                        },
                                        {
                                            "x": 348.0,
                                            "y": 194.0
                                        },
                                        {
                                            "x": 348.0,
                                            "y": 266.0
                                        },
                                        {
                                            "x": 286.0,
                                            "y": 266.0
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    "mobile": [
                        {
                            "text": "010-1234-5678",
                            "boundingPolys": [
                                {
                                    "vertices": [
                                        {
                                            "x": 297.0,
                                            "y": 183.0
                                        },
                                        {
                                            "x": 396.0,
                                            "y": 183.0
                                        },
                                        {
                                            "x": 396.0,
                                            "y": 305.0
                                        },
                                        {
                                            "x": 297.0,
                                            "y": 305.0
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    "tel": [
                        {
                            "text": "123-4567-8901",
                            "boundingPolys": [
                                {
                                    "vertices": [
                                        {
                                            "x": 338.0,
                                            "y": 189.0
                                        },
                                        {
                                            "x": 414.0,
                                            "y": 189.0
                                        },
                                        {
                                            "x": 414.0,
                                            "y": 288.0
                                        },
                                        {
                                            "x": 338.0,
                                            "y": 288.0
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    "fax": [],
                    "email": [],
                    "homepage": []
                }
            },
            "uid": "3277149ad2324de0b412669f7eac474a",
            "name": "testV2Demo",
            "inferResult": "SUCCESS",
            "message": "SUCCESS",
            "validationResult": {
                "result": "NO_REQUESTED"
            }
        }
    ]
}

id card 응답 예시

{
    "version": "V2",
    "requestId": "string",
    "timestamp": 1613984543939,
    "images": [
        {
            "idCard": {
                "meta": {
                    "estimatedLanguage": "ko"
                },
                "result": {
                    "isConfident": true,
                    "ic": {
                        "name": [
                            {
                                "text": "소닉",
                                "formatted": {
                                    "value": "소닉"
                                },
                                "boundingPolys": [
                                    {
                                        "vertices": [
                                            {
                                                "x": 93.0,
                                                "y": 135.0
                                            },
                                            {
                                                "x": 257.0,
                                                "y": 135.0
                                            },
                                            {
                                                "x": 257.0,
                                                "y": 161.0
                                            },
                                            {
                                                "x": 93.0,
                                                "y": 161.0
                                            }
                                        ]
                                    }
                                ]
                            }
                        ],
                        "personalNum": [
                            {
                                "text": "910623-1062372",
                                "formatted": {
                                    "value": "910623-1062372"
                                },
                                "boundingPolys": [
                                    {
                                        "vertices": [
                                            {
                                                "x": 83.0,
                                                "y": 166.0
                                            },
                                            {
                                                "x": 260.0,
                                                "y": 166.0
                                            },
                                            {
                                                "x": 260.0,
                                                "y": 186.0
                                            },
                                            {
                                                "x": 83.0,
                                                "y": 186.0
                                            }
                                        ]
                                    }
                                ]
                            }
                        ],
                        "address": [
                            {
                                "text": "서울특별시 종로구 종로1가 24 르메이에르 종로타운",
                                "formatted": {
                                    "value": "서울특별시 종로구 종로1가 24 르메이에르 종로타운"
                                },
                                "boundingPolys": [
                                    {
                                        "vertices": [
                                            {
                                                "x": 43.0,
                                                "y": 232.0
                                            },
                                            {
                                                "x": 148.0,
                                                "y": 232.0
                                            },
                                            {
                                                "x": 148.0,
                                                "y": 255.0
                                            },
                                            {
                                                "x": 43.0,
                                                "y": 255.0
                                            }
                                        ]
                                    },
                                    {
                                        "vertices": [
                                            {
                                                "x": 47.0,
                                                "y": 212.0
                                            },
                                            {
                                                "x": 150.0,
                                                "y": 212.0
                                            },
                                            {
                                                "x": 150.0,
                                                "y": 234.0
                                            },
                                            {
                                                "x": 47.0,
                                                "y": 234.0
                                            }
                                        ]
                                    },
                                    {
                                        "vertices": [
                                            {
                                                "x": 154.0,
                                                "y": 232.0
                                            },
                                            {
                                                "x": 240.0,
                                                "y": 232.0
                                            },
                                            {
                                                "x": 240.0,
                                                "y": 255.0
                                            },
                                            {
                                                "x": 154.0,
                                                "y": 255.0
                                            }
                                        ]
                                    },
                                    {
                                        "vertices": [
                                            {
                                                "x": 156.0,
                                                "y": 212.0
                                            },
                                            {
                                                "x": 219.0,
                                                "y": 212.0
                                            },
                                            {
                                                "x": 219.0,
                                                "y": 234.0
                                            },
                                            {
                                                "x": 156.0,
                                                "y": 234.0
                                            }
                                        ]
                                    },
                                    {
                                        "vertices": [
                                            {
                                                "x": 224.0,
                                                "y": 212.0
                                            },
                                            {
                                                "x": 302.0,
                                                "y": 212.0
                                            },
                                            {
                                                "x": 302.0,
                                                "y": 235.0
                                            },
                                            {
                                                "x": 224.0,
                                                "y": 235.0
                                            }
                                        ]
                                    },
                                    {
                                        "vertices": [
                                            {
                                                "x": 305.0,
                                                "y": 213.0
                                            },
                                            {
                                                "x": 333.0,
                                                "y": 213.0
                                            },
                                            {
                                                "x": 333.0,
                                                "y": 234.0
                                            },
                                            {
                                                "x": 305.0,
                                                "y": 234.0
                                            }
                                        ]
                                    }
                                ]
                            }
                        ],
                        "issueDate": [
                            {
                                "text": "2011.3. 6.",
                                "formatted": {
                                    "year": "2011",
                                    "month": "03",
                                    "day": "06"
                                },
                                "boundingPolys": [
                                    {
                                        "vertices": [
                                            {
                                                "x": 261.0,
                                                "y": 314.0
                                            },
                                            {
                                                "x": 351.0,
                                                "y": 314.0
                                            },
                                            {
                                                "x": 351.0,
                                                "y": 336.0
                                            },
                                            {
                                                "x": 261.0,
                                                "y": 336.0
                                            }
                                        ]
                                    },
                                    {
                                        "vertices": [
                                            {
                                                "x": 354.0,
                                                "y": 314.0
                                            },
                                            {
                                                "x": 376.0,
                                                "y": 314.0
                                            },
                                            {
                                                "x": 376.0,
                                                "y": 334.0
                                            },
                                            {
                                                "x": 354.0,
                                                "y": 334.0
                                            }
                                        ]
                                    }
                                ]
                            }
                        ],
                        "authority": [
                            {
                                "text": "소닉대통령추진회 소덕회장",
                                "formatted": {
                                    "value": "소닉대통령추진회 소덕회장"
                                },
                                "boundingPolys": [
                                    {
                                        "vertices": [
                                            {
                                                "x": 172.0,
                                                "y": 338.0
                                            },
                                            {
                                                "x": 346.0,
                                                "y": 338.0
                                            },
                                            {
                                                "x": 346.0,
                                                "y": 366.0
                                            },
                                            {
                                                "x": 172.0,
                                                "y": 366.0
                                            }
                                        ]
                                    },
                                    {
                                        "vertices": [
                                            {
                                                "x": 347.0,
                                                "y": 338.0
                                            },
                                            {
                                                "x": 435.0,
                                                "y": 336.0
                                            },
                                            {
                                                "x": 435.0,
                                                "y": 363.0
                                            },
                                            {
                                                "x": 348.0,
                                                "y": 365.0
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    },
                    "idtype": "ID Card"
                }
            },
            "uid": "0012374f247f4e70966d35eaa3c41d2a",
            "name": "testV2Demo",
            "inferResult": "SUCCESS",
            "message": "SUCCESS",
            "validationResult": {
                "result": "NO_REQUESTED"
            }
        }
    ]
}

medical receipt 응답 예시

{
  "version": "V2",
  "requestId": "string",
  "timestamp": 1621394368343,
  "images": [
    {
      "medicalReceipt": {
        "result": [
          {
            "id": 60,
            "keyTexts": "선택항목|비급여|계",
            "valueText": "53435",
            "confidence": 0.9542916,
            "keyCells": [
              {
                "boundingPoly": {
                  "vertices": [
                    {
                      "x": 303,
                      "y": 16
                    },
                    {
                      "x": 596,
                      "y": 16
                    },
                    {
                      "x": 596,
                      "y": 33
                    },
                    {
                      "x": 303,
                      "y": 33
                    }
                  ]
                },
                "depth": 1,
                "formatted": "선택항목",
                "group": "column",
                "value": "선택항목"
              },
              {
                "boundingPoly": {
                  "vertices": [
                    {
                      "x": 513,
                      "y": 34
                    },
                    {
                      "x": 598,
                      "y": 34
                    },
                    {
                      "x": 598,
                      "y": 50
                    },
                    {
                      "x": 513,
                      "y": 50
                    }
                  ]
                },
                "depth": 2,
                "formatted": "비급여",
                "group": "column",
                "value": "비급여"
              }
            ],
            "valueCell": {
              "boundingPoly": {
                "vertices": [
                  {
                    "x": 513,
                    "y": 195
                  },
                  {
                    "x": 597,
                    "y": 195
                  },
                  {
                    "x": 597,
                    "y": 212
                  },
                  {
                    "x": 513,
                    "y": 212
                  }
                ]
              },
              "confidence": 0.9542916,
              "value": "53435"
            }
          }
        ],
        "checksum": {
          "sumPaidByPatient": {
            "found": false,
            "foundValueIds": [],
            "foundValueSum": 0,
            "foundTotalIds": [],
            "foundTotalSum": 0,
            "difference": 0
          },
          "sumPaidByInsurer": {
            "found": false,
            "foundValueIds": [],
            "foundValueSum": 0,
            "foundTotalIds": [],
            "foundTotalSum": 0,
            "difference": 0
          },
          "sumPaidByPatientFull": {
            "found": false,
            "foundValueIds": [],
            "foundValueSum": 0,
            "foundTotalIds": [],
            "foundTotalSum": 0,
            "difference": 0
          },
          "sumTreatmentCost": {
            "found": false,
            "foundValueIds": [],
            "foundValueSum": 0,
            "foundTotalIds": [],
            "foundTotalSum": 0,
            "difference": 0
          },
          "sumTreatmentCostEtc": {
            "found": false,
            "foundValueIds": [],
            "foundValueSum": 0,
            "foundTotalIds": [],
            "foundTotalSum": 0,
            "difference": 0
          },
          "totalAmount": {
            "found": true,
            "foundValueIds": [],
            "foundValueSum": 0,
            "foundTotalIds": [
              40
            ],
            "foundTotalSum": 1541717,
            "difference": 1541717
          },
          "totalPaid": {
            "found": true,
            "foundValueIds": [],
            "foundValueSum": 0,
            "foundTotalIds": [
              84
            ],
            "foundTotalSum": 102130,
            "difference": 102130
          }
        }
      },
      "uid": "ef80a5d290284373acad3ba23cb4edfc",
      "name": "test 1",
      "inferResult": "SUCCESS",
      "message": "SUCCESS",
      "validationResult": {
        "result": "NO_REQUESTED"
      }
    }
  ]
}

API 예제

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

  • Request with 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 OCRAPIDemo {

	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;
  }
?>
  • Request with 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 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_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()
        }
    ],
    '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_file = "YOUR_IMAGE_FILE";

  $params->version = "V2";
  $params->requestId = "uuid";
  $params->timestamp = time();
  $image->format = "jpg";
  $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()
%>

Error code

HttpStatusCode Description
400 Request parameters invalid or constraint problem.
401 Api secret(X-CHATBOT-API-KEY) wrong
500 Internal server error

Error Response Body:

{
  "code": "Error Code",
  "message": "error details message.",
  "path": "request API path",
  "timestamp": 1570776853475
}
ErrorCode Description
0001 URL is invalid.
0002 Secret key validate failed.
0011 Request body invalid.
0021 Protocol version not support.
0022 Request domain invalid.
0023 API request count reach the upper limit.
0025 Calls to this api have exceeded the rate limit.
0500 Unknown service error.
0501 OCR Service error.

이 문서가 도움이 되었습니까?

Changing your password will log you out immediately. Use the new password to log back in.
First name must have atleast 2 characters. Numbers and special characters are not allowed.
Last name must have atleast 1 characters. Numbers and special characters are not allowed.
Enter a valid email
Enter a valid password
Your profile has been successfully updated.