Created
February 9, 2023 20:56
-
-
Save skanga/5d74f24acd36bd8d15bc71492b283d1b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.json.JSONArray; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import java.io.BufferedInputStream; | |
import java.io.BufferedReader; | |
import java.io.DataOutputStream; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import java.nio.file.Files; | |
import java.util.Map; | |
public class PostMultipart | |
{ | |
private final static String API_KEY = "helloworld"; // TODO: Change this to your own API key | |
private final static String IMAGE_FILE = "test.png"; // TODO: Change this to your own image file | |
private final static String OCR_URL = "https://api.ocr.space/parse/image"; // OCR API Endpoint | |
private final static String USER_AGENT = "Mozilla/5.0"; // User-Agent to use for HTTP requests | |
private final static String PARSE_LANG = "eng"; // Language to be used for parsing | |
private final static String USE_OVERLAY = "true"; // Request overlay information | |
private final String boundary = "*****"; | |
private final String crlf = "\r\n"; | |
private final String twoHyphens = "--"; | |
private final HttpURLConnection httpConn; | |
private final DataOutputStream requestStream; | |
public static void main(String[] args) throws IOException | |
{ | |
long startTime = System.currentTimeMillis(); | |
PostMultipart multipartUtility = new PostMultipart(OCR_URL, null); | |
multipartUtility.addFormField("apikey", API_KEY); | |
multipartUtility.addFormField("language", PARSE_LANG); | |
multipartUtility.addFormField("isOverlayRequired", USE_OVERLAY); | |
multipartUtility.addFormField("apikey", API_KEY); | |
multipartUtility.addFilePart("file", new File (IMAGE_FILE)); | |
JSONObject jsonData = multipartUtility.finish(); | |
//System.out.println(jsonData.toString()); | |
handleJSONResponse(jsonData); | |
System.out.println("Elapsed time: " + (System.currentTimeMillis() - startTime) + " ms"); | |
} | |
private static void handleJSONResponse(JSONObject response) throws JSONException | |
{ | |
if (response.has("ParsedText")) | |
{ | |
JSONArray overlay = response.getJSONObject("TextOverlay").getJSONArray("Lines"); | |
System.out.println("TextOverlay returned " + overlay.length() + " Lines"); | |
for (int i = 0; i < overlay.length(); i++) | |
{ | |
JSONObject currObj = overlay.getJSONObject(i); | |
JSONArray words = currObj.getJSONArray("Words"); | |
System.out.println("Line " + i + " (" + words.length() + " words) -> " + currObj.getString("LineText") + " (H:" + currObj.getInt("MaxHeight") + " T:" + currObj.getInt("MinTop") + ")"); | |
for (int x = 0; x < words.length(); x++) | |
System.out.println("Line " + i + ", Word " + x + ": " + words.getJSONObject(x).getString("WordText") + " (L:" + words.getJSONObject(x).getInt("Left") + ", T:" + words.getJSONObject(x).getInt("Top") + ", H:" + words.getJSONObject(x).getInt("Height") + ", W:" + words.getJSONObject(x).getInt("Width") + ")"); | |
} | |
// System.out.println("ParsedText: " + response.getString("ParsedText")); | |
} | |
else if (response.has("ErrorMessage")) | |
{ | |
String error = response.getString("ErrorMessage"); | |
System.out.println("ErrorMessage: " + error); | |
} | |
} | |
/** | |
* This constructor initializes a new HTTP POST request with content type is set to multipart/form-data | |
*/ | |
public PostMultipart(String requestURL, Map<String, String> requestProps) throws IOException | |
{ | |
// creates a unique boundary based on time stamp | |
URL url = new URL(requestURL); | |
httpConn = (HttpURLConnection) url.openConnection(); | |
httpConn.setUseCaches(false); | |
httpConn.setDoOutput(true); // indicates POST method | |
httpConn.setDoInput(true); | |
httpConn.setRequestMethod("POST"); | |
httpConn.setRequestProperty("Connection", "Keep-Alive"); | |
httpConn.setRequestProperty("Cache-Control", "no-cache"); | |
httpConn.setRequestProperty("User-Agent", USER_AGENT); | |
if (requestProps != null) | |
{ | |
for (Map.Entry<String, String> entry : requestProps.entrySet()) | |
{ | |
httpConn.setRequestProperty(entry.getKey(), entry.getValue()); | |
} | |
} | |
httpConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + this.boundary); | |
requestStream = new DataOutputStream(httpConn.getOutputStream()); | |
} | |
/** | |
* Adds a form field to the request | |
*/ | |
public void addFormField(String name, String value) throws IOException | |
{ | |
requestStream.writeBytes(this.twoHyphens + this.boundary + this.crlf); | |
requestStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + this.crlf); | |
requestStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + this.crlf); | |
requestStream.writeBytes(this.crlf); | |
requestStream.writeBytes(value + this.crlf); | |
requestStream.flush(); | |
} | |
/** | |
* Adds an upload file section to the request | |
* | |
* @param fieldName name attribute in <input type="file" name="..." /> | |
* @param uploadFile a File to be uploaded | |
*/ | |
public void addFilePart(String fieldName, File uploadFile) throws IOException | |
{ | |
String fileName = uploadFile.getName(); | |
requestStream.writeBytes(this.twoHyphens + this.boundary + this.crlf); | |
requestStream.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + fileName + "\"" + this.crlf); | |
requestStream.writeBytes(this.crlf); | |
byte[] bytes = Files.readAllBytes(uploadFile.toPath()); | |
requestStream.write(bytes); | |
requestStream.flush(); | |
} | |
/** | |
* Completes the request and returns the JSON response from the server. | |
*/ | |
public JSONObject finish() throws IOException | |
{ | |
String responseMessage; | |
requestStream.writeBytes(crlf); | |
requestStream.writeBytes(twoHyphens); | |
requestStream.writeBytes(boundary); | |
requestStream.writeBytes(twoHyphens); | |
requestStream.writeBytes(crlf); | |
requestStream.flush(); | |
requestStream.close(); | |
// checks server's status code first | |
int responseStatus = httpConn.getResponseCode(); | |
if (responseStatus == HttpURLConnection.HTTP_OK) | |
{ | |
InputStream responseStream = new BufferedInputStream(httpConn.getInputStream()); | |
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream)); | |
String line; | |
StringBuilder stringBuilder = new StringBuilder(); | |
while ((line = responseStreamReader.readLine()) != null) | |
{ | |
stringBuilder.append(line).append("\n"); | |
} | |
responseStreamReader.close(); | |
responseMessage = stringBuilder.toString(); | |
httpConn.disconnect(); | |
} | |
else | |
{ | |
throw new IOException("Server returned non-OK status: " + responseStatus); | |
} | |
JSONObject jsonData = new JSONObject(responseMessage); | |
// Filter the return values to results and errors | |
if (jsonData.has("ParsedResults")) | |
return jsonData.getJSONArray("ParsedResults").getJSONObject(0); | |
else if (jsonData.has("IsErroredOnProcessing") && jsonData.getBoolean("IsErroredOnProcessing")) | |
return jsonData; | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment