如何使用base 64调用ocr.space API

时间:2019-06-25 17:37:39

标签: java java-8 base64

我想使用Java以64为基数调用ocr.space(https://ocr.space/ocrapi)OCR API。

我使用了以下代码,但是输出出错。

我使用过的代码...

try {
        URL obj = new URL("https://api.ocr.space/parse/image"); // OCR API Endpoints

        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        con.setRequestProperty("apikey", "******");

        con.setDoOutput(true);
        File file = new File("C:\\App_development\\OCRIMG.JPG");
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        InputStream finput = new FileInputStream(file);
        byte[] imageBytes = new byte[(int)file.length()];
        finput.read(imageBytes, 0, imageBytes.length);
        finput.close();
        String imageStr = Base64.encodeBase64String(imageBytes);
        wr.writeBytes(imageStr);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();


        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());
    }
    catch(Exception exx)
    {
        exx.printStackTrace();
    }

我得到的异常

Response Code : 200
{"OCRExitCode":0,"IsErroredOnProcessing":false,"ErrorMessage":["Parameter name '/9j/……..' is invalid. Valid parameters: apikey,url,language,isoverlayrequired,base64image,iscreatesearchablepdf,issearchablepdfhidetextlayer,filetype,addressparsing,scale,detectorientation,istable,ocrengine,detectcheckbox,checkboxtemplate","Please check if you need to URL encode the URL passed in request parameters."],"ProcessingTimeInMilliseconds":"4"}

任何帮助都将受到高度重视...。

2 个答案:

答案 0 :(得分:0)

您在这里看到Java sample code了吗?

您是否要上传文件使用Base64字符串。如果是base64字符串,那么您需要使用“ base64image”参数。这是base64 test string。您可以先在Postman中对其进行测试,

答案 1 :(得分:0)

也许您可以更改

String imageStr = Base64.encodeBase64String(imageBytes);

 String imageStr ="&base64image="+ Base64.encodeBase64String(imageBytes)+":<JPG>";

但我见面

{"OCRExitCode":99,"IsErroredOnProcessing":true,"ErrorMessage":["Some internal processing error occurred. Please give us some time, we are looking into this!"],"ErrorDetails":"","ProcessingTimeInMilliseconds":"0"}

我不知道为什么.............

也许您可以参考以下内容: https://github.com/bsuhas/OCRTextRecognitionAndroidApp/blob/be7bb24a0e880cf174de9f16047fcb1b8c7447c6/app/src/main/java/com/ocrtextrecognitionapp/OCRAsyncTask.java