1

"No file uploaded or URL provided" when calling ocr.space API

I would like to know how can we upload file to server as sent in above url, that code is in C# but I want it in Java for android

The code which I have is

`final HttpClient httpclient = new DefaultHttpClient();
            final HttpPost httppost = new HttpPost("https://api.ocr.space/parse/image");

            //httppost.addHeader("User-Agent", "Mozilla/5.0");
            //httppost.addHeader("Accept-Language", "en-US,en;q=0.5");
              //con.setRequestMethod("POST");
               // con.setRequestProperty("User-Agent", "Mozilla/5.0");
               // con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            final FileBody image = new FileBody(new File(fileName));

            final MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("isOverlayRequired", new StringBody(Boolean.toString(isOverlayRequired)));
            reqEntity.addPart("language", new StringBody(langCode));
            reqEntity.addPart("apikey", new StringBody(apiKey));
            reqEntity.addPart("file",image);
            httppost.setEntity(reqEntity);

            final HttpResponse response = httpclient.execute(httppost);
            final HttpEntity resEntity = response.getEntity();
            final StringBuilder sb = new StringBuilder();
            if (resEntity != null) {
                final InputStream stream = resEntity.getContent();
                byte bytes[] = new byte[4096];
                int numBytes;
                while ((numBytes=stream.read(bytes))!=-1) {
                    if (numBytes!=0) {
                        sb.append(new String(bytes, 0, numBytes));
                    }
                }
            }

            Log.i("data", sb.toString());`

but it gives exception as

javax.net.ssl.SSLException: hostname in certificate didn't match: <api.ocr.space> != <ocr.a9t9.com> OR <ocr.a9t9.com> OR <www.ocr.a9t9.com>
Community
  • 1
  • 1
Colthurling
  • 75
  • 1
  • 1
  • 7

2 Answers2

2

Below is my main code:

private String sendPost(boolean isOverlayRequired, File imageUrl, String language) throws Exception {

        StringBuffer responseString = new StringBuffer();
        try {
            MultipartUtility multipart = new MultipartUtility(url, "UTF-8");

            multipart.addFormField("isOverlayRequired", Boolean.toString(isOverlayRequired));
            multipart.addFilePart("file", imageUrl);
            List<String> response = multipart.finish();

            for (String line : response) {
                responseString.append(line);
            }
        } catch (IOException ex) {
            Log.v("OCR Exception",ex.getMessage());
        }

        //return result
        return String.valueOf(responseString);
    }

API key should be added to header. I have added that inside MultiPartUtility code itself. Below is my code:

package com.example.ab00428268.virtualassistant.Utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;

/**
 * This constructor initializes a new HTTP POST request with content type
 * is set to multipart/form-data
 * @param requestURL
 * @param charset
 * @throws IOException
 */
public MultipartUtility(String requestURL, String charset)
        throws IOException {
    this.charset = charset;

    // creates a unique boundary based on time stamp
    boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("User-Agent", "Mozilla/5.0");
    httpConn.setRequestProperty("apikey", "YourAPIKey");
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
            true);
   }

   public void addFormField(String name, String value) {
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
            .append(LINE_FEED);
    writer.append("Content-Type: text/plain; charset=" + charset).append(
            LINE_FEED);
    writer.append(LINE_FEED);
    writer.append(value).append(LINE_FEED);
    writer.flush();
   }


  public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
                    + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
                    + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    Log.v("MultiPart",fileName);
    Log.v("MultiPart",uploadFile.getPath());
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();
   }


   public void addHeaderField(String name, String value) {
    writer.append(name + ": " + value).append(LINE_FEED);
    writer.flush();
   }


  public List<String> finish() throws IOException {
    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    Log.v("MultiPart",""+httpConn.getResponseMessage());
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            Log.v("MultiPart",""+line);
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
     } else {
        throw new IOException("Server returned non-OK status: " + status);
     }

    return response;
   }
  }
Abhishek
  • 61
  • 11
0

you can try the given link

but this site provides the example with uri not with file.

Try this code it worked for me.

String charset = "UTF-8";
File uploadFile1 = new File(fileName);

String requestURL = "https://api.ocr.space/parse/image";

try {
    MultipartUtility multipart = new MultipartUtility(requestURL, charset);

    multipart.addHeaderField("User-Agent", "Mozilla/5.0");
    multipart.addHeaderField("Accept-Language", "en-US,en;q=0.5");

    multipart.addFormField("apikey", apiKey);
    multipart.addFormField("isOverlayRequired", Boolean.toString(isOverlayRequired));
    multipart.addFormField("language", langCode);
    multipart.addFilePart("file", uploadFile1);


    List<String> response = multipart.finish();

    System.out.println("SERVER REPLIED:");

    for (String line : response) {
        System.out.println(line);
    }
} catch (IOException ex) {
    System.err.println(ex);
}
Durgesh Kumar
  • 935
  • 10
  • 17