java - 上传文件到 ocr.space api

标签 java android ocr

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

我想知道我们如何将文件上传到上面 url 中发送的服务器,该代码在 C# 中,但我希望它在 Android 的 Java 中

我的代码是

`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());`

但它给出了异常(exception)

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>

最佳答案

下面是我的主要代码:

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 应添加到标题中。我已经在 MultiPartUtility 代码本身中添加了它。下面是我的代码:

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;
   }
  }

关于java - 上传文件到 ocr.space api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37463910/

相关文章:

android - 使用本地 SQlite 数据库填充可扩展 ListView 的方法

php - 检测图像中的噪声/伪影

java - 开发网络游戏

java - 动态数据源作为 Spring Boot + Hibernate 中的第二个数据源

java - 未找到代理 JAR 或没有代理类属性

java - 将html代码转换为纯文本

java - handshake_failure 找不到合适的证书

android - 在 PreferenceFragmentCompat 中动态膨胀首选项

ios - Tesseract OCR 无法识别除法符号 "÷"

用于矢量 PDF 的 Azure 读取 API